繁体   English   中英

双循环列表理解

[英]Double for loop list comprehension

我正在尝试使用列表推导进行以下操作:

Input: [['hello ', 'world '],['foo ',' bar']]
Output: [['hello', 'world'], ['foo', 'bar']]

以下是没有列表推导式的方法:

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']]

我如何使用列表推导来做到这一点?

a = [['hello ', 'world '],['foo ',' bar']]
b = [[s.strip() for s in l] for l in a]
print(b)
# [['hello', 'world'], ['foo', 'bar']]

简单地将下一个list理解作为更大list理解的每个元素:

>>> i = [['hello ', 'world '],['foo ',' bar']]
>>> o = [[element.strip() for element in item] for item in i]
>>> o
[['hello', 'world'], ['foo', 'bar']]

或者使用list()map()

>>> i = [['hello ', 'world '],['foo ',' bar']]
>>> o = [list(map(str.strip, item)) for item in i]
>>> o
[['hello', 'world'], ['foo', 'bar']]

像这样的东西?

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.

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