[英]How to achieve two separate list of lists from a single list of lists of tuple with list comprehension?
說,我有兩個2D列表,如下所示:
[[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
我想要實現的輸出是:
Output_list=[['1','12','3'], ['21','31'], ['11']]
這里的主要復雜性是我想通過單個list comprehension
來實現輸出。
我的一個嘗試是:
print [a for innerList in fin_list1 for a,b in innerList]
輸出:
['1', '12', '3', '21', '31', '11']
但是,正如您所看到的,雖然我已成功檢索每個元組的第二個元素,但我未能保留內部列表結構。
我們從這開始:
>>> l = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
最初你試圖沿着這些方向做一些事情:
>>> [y for sublist in l for x, y in sublist]
['1', '12', '3', '21', '31', '11']
這里的錯誤是這個列表理解是一維的,即所有的值都只是整數而不是列表本身
為了使這個二維,我們的值需要是列表。 最簡單的方法是讓我們的值表達式成為嵌套列表解析,迭代原始列表的子列表元素:
>>> [[y for x, y in sublist] for sublist in l]
[['1', '12', '3'], ['21', '31'], ['11']]
從技術上講,這是兩個列表理解,但顯然列表理解可以用map
代替,如Roberto的答案中所解釋的那樣。
首先,讓我們分配數據:
>>> data = [
[('a', '1'), ('a', '12'), ('a', '3')],
[('b', '21'), ('b', '31')],
[('c', '11')],
]
您可以使用itemgetter
創建一個從元組中獲取一個元素的函數:
>>> from operator import itemgetter
>>> first = itemgetter(0)
>>> second = itemgetter(1)
現在您可以使用map
轉換內部列表:
>>> [map(first, row) for row in data]
[['a', 'a', 'a'], ['b', 'b'], ['c']]
>>> [map(second, row) for row in data]
[['1', '12', '3'], ['21', '31'], ['11']]
你也可以在不使用itemgetter
情況下創建first
和second
:
def first(xs):
return xs[0]
def second(xs):
return xs[1]
the_list = [[('a', '1'), ('a', '12'), ('a', '3')], [('b', '21'), ('b', '31')], [ ('c', '11')]]
new_list = [[x[1] for x in y] for y in the_list]
print new_list
輸出:
[['1','12','3'],['21','31'],['11']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.