[英]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. 逻辑是用一个新项替换4个连续的重复空字符串'' ,同时保留其余的项目。
['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
: 你的最内层循环不会产生任何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: 你需要包括LOL
与长组y
的4及以上,以及一切用原来的,并总是重复:
[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: 因此,上面要么包含x * y
, y < 4
,否则它将包含'LOL' * (y // 4)
以用于其他任何内容:
>>> [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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.