[英]Convert nested for loop to list comprehension
I made for loop code like this: 我做了这样的循环代码:
all = []
for sen_list in sen_lists:
te = []
for ele in sen_list:
boolean = ele == "."
te.append(boolean)
all.append(te)
sen_lists = [['a', 'b', 'c', 'd', '.', '.'], ['e', 'f', 'g', 'h']]
upper code works well... but I want to convert list comprehension code. 上层代码效果很好...但是我想转换列表理解代码。
I try like this: 我这样尝试:
[ele == "." for sen_list in rawdf.TEXT[:10] for ele in sen_list]
but this code is doesn't work. 但是此代码不起作用。
please let me know. 请告诉我。 thanks.
谢谢。
Consider a nested list comprehension. 考虑嵌套列表理解。 Or, in other words, a list comprehension of list comprehensions.
换句话说,就是列表理解的列表理解。
The inner one represents your inner for
loop. 内层代表您的内层
for
循环。 The outer one represents your outer for
loop. 外部代表您的外部
for
循环。
sen_lists = [['a', 'b', 'c', 'd', '.', '.'], ['e', 'f', 'g', 'h']]
res = [[ele == "." for ele in sen_list] for sen_list in sen_lists]
# [[False, False, False, False, True, True], [False, False, False, False]]
You need to wrap you boolean logic in [ ] so that boolean =
knows what it is supposed to equal. 您需要将布尔逻辑包装在[]中,以便
boolean =
知道应该等于什么。
boolean = [ele == '.']
I don't know the logic to do it all on one line, like you're trying to do at the end of your question.. would be cool though. 我不知道在一件事上做所有事情的逻辑,就像您在问题的末尾尝试做的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.