假设我有这种数据格式
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]]
""""
答案 0 :(得分:0)
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)]]]
答案 1 :(得分:0)
代码就像嵌套的for循环一样简单
thingy=[[[(1,2),(3,4)],[(5,6),(7,8)]],[[(-1,-2),(-3,-4)],[(-5,-6),(-7,-8)]]]
for i in thingy:
for e in i:
e.append((9,9))
如果您需要保留旧列表,只需弄乱这样的副本:
thingy_copy = thingy[:]
for i in thingy:
for e in i:
e.append((9,9))