2015-10-21 81 views
1

我嘗試使用列表理解做以下操作:雙for循環列表理解

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

我怎樣才能做到這一點使用列表解析?

回答

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

我會接受這個,因爲這是第一個答案。謝謝。 – Sait

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

這樣的事情?

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

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

print output 


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