如何将元组附加到子子列表?(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 thoughI 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)]]]更多推荐
发布评论