我是編程新手,需要一些幫助。 我有這樣如何將列表列表轉換爲列表列表?
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
列表,我試圖擺脫的元組,同時保留在列表中的數據,其結果應該是這樣的
output=[['the', 'b', 'hotel', 'i'],['the', 'b', 'staff', 'i']]
太謝謝你了
我是編程新手,需要一些幫助。 我有這樣如何將列表列表轉換爲列表列表?
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
列表,我試圖擺脫的元組,同時保留在列表中的數據,其結果應該是這樣的
output=[['the', 'b', 'hotel', 'i'],['the', 'b', 'staff', 'i']]
太謝謝你了
你可以做下面的列表理解:
>>> [[y for x in i for y in x] for i in a]
[['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
請注意,這與元組無關,因爲鴨子輸入的處理方式與列表理解中的列表完全相同。您實質上是通過Making a flat list out of list of lists in Python中的多個列表項執行操作。
這可以通過sum
函數來完成:
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
output = [sum(elem,()) for elem in a]
print(output)
如果它必須返回一個列表:
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
output = [sum(map(list,elem), []) for elem in a]
print(output)
@PedroLobito感謝您的輸入,我更新了它。 – Neil
我想你可以使用:
output = []
for x in a:
output.append([element for tupl in x for element in tupl])
輸出:
[['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
這裏是@nfn尼爾A.
from itertools import repeat
list(map(list, map(sum, a, repeat(()))))
# -> [['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
你缺少你搜索的是「扁平化」的關鍵字的「功能性」風格的變體,如「如何扁平化列表」。 – Prune