双for循环列表理解
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]]
我正在尝试使用列表理解来执行以下操作:
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]]