如何将元组附加到子子列表?(How to append tuple to sub

编程入门 行业动态 更新时间:2024-10-26 20:31:35
如何将元组附加到子子列表?(How to append tuple to sub-sub-list?)

假设我有这种数据格式

thingy=[[[(1,2),(3,4)],[(5,6),(7,8)]],[[(-1,-2),(-3,-4)],[(-5,-6),(-7,-8)]]]

我想将(9,9)追加到每个子子列表中,以便:

thingy_2=[[[(1,2),(3,4),(9,9)],[(5,6),(7,8),(9,9)]],[[(-1,-2),(-3,-4),(9,9)],[(-5,-6),(-7,-8),(9,9)]]]

有没有办法做以下事情:

thingy_2=[[i for i in j].append((9,9)) for j in thingy] #this doesn't work though

我知道如果我这样做:

[[i.append((9,9)) for i in j] for j in thingy]

这将附加(9,9)到thingy列表但不会帮助我创建一个新列表。

thingy_2=[[i.append((9,9)) for i in j] for j in thingy] """ In [302]: thingy_2 Out[301]: [[None, None], [None, None]] """"

Suppose I have this data format

thingy=[[[(1,2),(3,4)],[(5,6),(7,8)]],[[(-1,-2),(-3,-4)],[(-5,-6),(-7,-8)]]]

and I want to append (9,9) to each sub-sub-list so as to have:

thingy_2=[[[(1,2),(3,4),(9,9)],[(5,6),(7,8),(9,9)]],[[(-1,-2),(-3,-4),(9,9)],[(-5,-6),(-7,-8),(9,9)]]]

Is there any way to do something like the following:

thingy_2=[[i for i in j].append((9,9)) for j in thingy] #this doesn't work though

I know that if I do:

[[i.append((9,9)) for i in j] for j in thingy]

This will append (9,9) to the thingy list but won't help me create a new list.

thingy_2=[[i.append((9,9)) for i in j] for j in thingy] """ In [302]: thingy_2 Out[301]: [[None, None], [None, None]] """"

最满意答案

append()对原始list执行操作,然后return值None 。 您需要添加或extend list 。 例如, [1,2] + [3,4]是[1,2,3,4] 。

>>> thingy=[[[(1,2),(3,4)],[(5,6),(7,8)]],[[(-1,-2),(-3,-4)],[(-5,-6),(-7,-8)]]] >>> thingy_2 = [[l + [(9,9)] for l in s] for s in thingy] >>> thingy_2 [[[(1, 2), (3, 4), (9, 9)], [(5, 6), (7, 8), (9, 9)]], [[(-1, -2), (-3, -4), (9, 9)], [(-5, -6), (-7, -8), (9, 9)]]]

append() carries out the operation on the original list, and then returns the value None. You need to add, or extend, the lists. For example, [1,2] + [3,4] is [1,2,3,4].

>>> thingy=[[[(1,2),(3,4)],[(5,6),(7,8)]],[[(-1,-2),(-3,-4)],[(-5,-6),(-7,-8)]]] >>> thingy_2 = [[l + [(9,9)] for l in s] for s in thingy] >>> thingy_2 [[[(1, 2), (3, 4), (9, 9)], [(5, 6), (7, 8), (9, 9)]], [[(-1, -2), (-3, -4), (9, 9)], [(-5, -6), (-7, -8), (9, 9)]]]

更多推荐

本文发布于:2023-07-28 01:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   列表   tuple   到子子   append

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!