[英]join sublist in a list of lists with python
I am a newbie to python and have been having an issue with list comprehension. 我是python的新手,并且列表理解一直存在问题。 Is there a way to extend subsists in a list of list like this
有没有办法在这样的列表中扩展存在
lst = [[0,0,0,0],[[x,x,x,x],[y,y,y,y]],[0,0,0,0],[0,0,0,0]]
I would like to end up with a following list, but I am not sure how to approach the problem: 我想以下面的列表结尾,但是我不确定如何解决该问题:
lst = [[0,0,0,0],[x,x,x,x,y,y,y,y],[0,0,0,0],[0,0,0,0]]
I found this snippet of code but I am not sure how to make it operate on a second "level" of lists. 我找到了这段代码,但是我不确定如何使它在列表的第二个“级别”上运行。 I tried this:
我尝试了这个:
print([x for y in lst for x in y])
Just go through each element and if it has a length of 2 (which means its a donut), add the two elements of that sublist together. 只需遍历每个元素,如果它的长度为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)
For the example given, you can do as follows: 对于给出的示例,您可以执行以下操作:
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]]
I assumed that x=1
, and y=2
. 我假设
x=1
,而y=2
。
Based on the image, it seems you have nested lists in the following way: 根据图像,您似乎可以通过以下方式嵌套列表:
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.