0

I am looking for some help here, I have a list which is exactly this

list like this: [1, 1, 1, 5, 5, 5, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8]

wanted result: [1, 5, 10, 10, 8, 8]

I have tried every possible way by iterating through the list 3 at a time and replacing only every third.

''.join([List[i] for i in range(len(List) - 1) if List[i + 1] != XX[i]] + [List[-1]])

I just can't get my head around it is there some python wizard who can do this?

Thanks

GabeTheApe
  • 348
  • 2
  • 13

2 Answers2

7

try

foo = [1, 1, 1, 5, 5, 5, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8]
print foo[::3]

This is called "list slicing". What this practically does is it prints out every third argument of your list starting from the first. This article Explain Python's slice notation explains the concept more thoroughly.

Community
  • 1
  • 1
Hannu
  • 11,685
  • 4
  • 35
  • 51
1

Code:

lst    = [1, 1, 1, 5, 5, 5, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8]
output = []

skip = 0
for idx, x in enumerate(lst):
    if skip:
        skip = skip - 1
        continue

    if (idx + 2) <= len(lst):
        if lst[idx] == lst[idx+1] and lst[idx] == lst[idx+2]:
            output.append(lst[idx])
            skip = skip + 2
    else:
        output.append(lst[idx])

print output
Jay Rajput
  • 1,813
  • 17
  • 23