[英]join sublist in a list of lists with python
我是python的新手,並且列表理解一直存在問題。 有沒有辦法在這樣的列表中擴展存在
lst = [[0,0,0,0],[[x,x,x,x],[y,y,y,y]],[0,0,0,0],[0,0,0,0]]
我想以下面的列表結尾,但是我不確定如何解決該問題:
lst = [[0,0,0,0],[x,x,x,x,y,y,y,y],[0,0,0,0],[0,0,0,0]]
我找到了這段代碼,但是我不確定如何使它在列表的第二個“級別”上運行。 我嘗試了這個:
print([x for y in lst for x in y])
只需遍歷每個元素,如果它的長度為2(這意味着它是一個甜甜圈),則將該子列表的兩個元素加在一起。
def flatten(data):
new_data = [lists[0]+lists[1] if len(lists) == 2 else lists for lists in data]
return new_data
data = [[1, 2, 3, 4], [[5, 6, 7, 8], [9, 10, 11, 12]], [13, 14, 15, 16]]
new_data = flatten(data)
對於給出的示例,您可以執行以下操作:
x,y=1,2
lst = [[0,0,0,0],[[x,x,x,x],[y,y,y,y]],[0,0,0,0],[0,0,0,0]]
map(lambda l: sum(l,[]) if isinstance(l[0],list) else l, lst)
#gives: [[0, 0, 0, 0], [1, 1, 1, 1, 2, 2, 2, 2], [0, 0, 0, 0], [0, 0, 0, 0]]
我假設x=1
,而y=2
。
根據圖像,您似乎可以通過以下方式嵌套列表:
x,y=1,2
lst = [[[0,0,0,0]],[[[x,x,x,x],[y,y,y,y]]],[[0,0,0,0]],[[0,0,0,0]]]
# 0, x, and y in you case are lists/touples, but for this example there are ints.
# it should not matter anyway for this example.
map(lambda l: [sum(l[0],[])] if len(l[0])==2 else l, lst)
# relults in: [[[0, 0, 0, 0]], [[1, 1, 1, 1, 2, 2, 2, 2]], [[0, 0, 0, 0]], [[0, 0, 0, 0]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.