将for循环转换为列表理解 [英] Convert a for loop to a list comprehension
问题描述
我有一个 for
循环,用于将字符串列表中每个元素的子字符串与另一个字符串列表中的元素进行比较.
mylist = []对于list1中的x:垫=错误对于list2中的y:如果x [:-14]在y中:垫=真如果不是垫子:mylist.append(x)
但是我想将其放在列表理解中(因为循环的使用并不符合我的喜好),但是找不到计算 mat
的方法./p>
我尝试过以下变化:
mylist = [如果list2中的x [:-14]为list1中x的x,则为x
但这与原始循环的逻辑不同.有没有办法将原始的for循环转换为列表理解?
在编写时,没有,您不能直接将其作为列表理解来编写.
但是,如果将 mat
的计算重写为单个表达式.(在这种情况下,您将使用 any
)
mylist = []对于list1中的x:mat = any((list2中y的((x [:-14] in y))如果不是垫子:mylist.append(x)
然后将该定义直接移至
条件:
mylist = []对于list1中的x:如果不存在((list2中y的((y中的x [:-14]))):mylist.append(x)
现在很容易进行转换:
mylist = [如果列表1中没有x,则表示列表1中x的x((列表2中的y中x [:-14]在y中))]
I have a for
loop that compares a substring of each element in a list of strings to the elements in another list of strings.
mylist = []
for x in list1:
mat = False
for y in list2:
if x[:-14] in y:
mat = True
if not mat:
mylist.append(x)
However I would like to put it in a list comprehension (for loops aren't as concise for my tastes) But can't find a way to do it with the calculation of mat
.
I have tried variations on:
mylist = [x for x in list1 if x[:-14] in list2]
But this is not the same logic as the original loop. Is there a way to reform the original for loop into list comprehension?
As it is written, no you cannot directly write it as a list comprehension.
however, if you rewrite the computation of mat
to be a single expression. (in this case, you would use any
)
mylist = []
for x in list1:
mat = any((x[:-14] in y) for y in list2)
if not mat:
mylist.append(x)
Then move that definition directly into the if not
condition:
mylist = []
for x in list1:
if not any((x[:-14] in y) for y in list2):
mylist.append(x)
Now it is pretty straight forward to convert:
mylist = [x for x in list1 if not any((x[:-14] in y) for y in list2)]
这篇关于将for循环转换为列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!