[英]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.