[英]Double for loop list comprehension
I am trying to do following operation using list comprehensions:我正在尝试使用列表推导进行以下操作:
Input: [['hello ', 'world '],['foo ',' bar']]
Output: [['hello', 'world'], ['foo', 'bar']]
Here is how one can do it without list comprehensions:以下是没有列表推导式的方法:
a = [['hello ', 'world '],['foo ',' bar']]
b = []
for i in a:
temp = []
for j in i:
temp.append( j.strip() )
b.append( temp )
print(b)
#[['hello', 'world'], ['foo', 'bar']]
How can I do it using list comprehensions?我如何使用列表推导来做到这一点?
a = [['hello ', 'world '],['foo ',' bar']]
b = [[s.strip() for s in l] for l in a]
print(b)
# [['hello', 'world'], ['foo', 'bar']]
Simply next one list
comprehension as each element of a larger list
comprehension:简单地将下一个list
理解作为更大list
理解的每个元素:
>>> i = [['hello ', 'world '],['foo ',' bar']]
>>> o = [[element.strip() for element in item] for item in i]
>>> o
[['hello', 'world'], ['foo', 'bar']]
Or use list()
and map()
:或者使用list()
和map()
:
>>> i = [['hello ', 'world '],['foo ',' bar']]
>>> o = [list(map(str.strip, item)) for item in i]
>>> o
[['hello', 'world'], ['foo', 'bar']]
something like this?像这样的东西?
input = [['hello ', 'world '], ['foo ',' bar']]
output = [[item.strip() for item in pair] for pair in input]
print output
[['hello', 'world'], ['foo', 'bar']]
grid = [[1,1,0],[0,1,0],[1,0,1]]
visited_arr = [[False for elm in i ]for i in grid]
print(visited_arr)
[[False,False, False],[False,False, False],[False,False, False]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.