简体   繁体   中英

List comprehension in python if/else

Input

['27', ' 5', '6', ' 0', ' 0', '', '', '', '','','','','','34','32','','','','']

I want my output to be something like this. The logic is to replace 4 consecutive duplicate empty strings ' ' with single new item while retaining the rest of the items.

['27', ' 5', '6', ' 0', ' 0', 'LOL','LOL', '34','32','LOL']

I'm confused as to why this only gives the output as

['LOL','LOL','LOL']

My code is as below:

from itertools import groupby,repeat
L =   ['27', ' 5', '6', ' 0', ' 0', '', '', '', '','','','','','34','32','','','','']
grouped_L = [(k, len(list(g))) for k,g in groupby(L)]

final_list = [z if x=='' else x   for x,y in grouped_L for z in repeat('LOL',(y//4))  ]
print(final_list)

Your innermost loop produces no results for any y < 4 :

>>> from itertools import repeat
>>> y = 4
>>> list(repeat('LOL', y // 4))
['LOL']
>>> y = 3
>>> list(repeat('LOL', y // 4))
[]

With no iterations, nothing will be added to the resulting list.

You'll need to use a different strategy; you'll need to include LOL for groups with length y of 4 and up, and for everything else use the original, and always repeat:

[value
 for x, y in grouped_L 
 for value in repeat(x if y < 4 else 'LOL', y if y < 4 else y // 4)]

So the above either includes x * y for y < 4 , otherwise it'll include 'LOL' * (y // 4) for anything else:

>>> [value
...  for x, y in grouped_L
...  for value in repeat(x if y < 4 else 'LOL', y if y < 4 else y // 4)]
['27', ' 5', '6', ' 0', ' 0', 'LOL', '34', '32', 'LOL']

Without list comprehensions but IMHO it is a much easier solution.

a = ['27', ' 5', '6', ' 0', ' 0', 'LOL', '34','32','LOL']

def remove_duplicates(w_duplicates):
    wo_duplicates = []
    for el in w_duplicates:
        if wo_duplicates and el == wo_duplicates[-1]:
            continue
        wo_duplicates.append(el)
    return wo_duplicates

print remove_duplicates(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM