我正在尝试使用列表推导进行以下操作:
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']]
如何使用列表推导来完成?
答案 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]]