双循环列表理解

时间:2015-10-21 01:13:26

标签: python list 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']]

如何使用列表推导来完成?

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

只需下一个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']]

答案 2 :(得分:1)

这样的事情?

input = [['hello ', 'world '], ['foo ',' bar']]

output = [[item.strip() for item in pair] for pair in input]

print output


[['hello', 'world'], ['foo', 'bar']]

答案 3 :(得分:0)

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