Python:能否在一行中拆包元组并将其附加到多个列表中?

9

在Python中,是否可以将元组解包并添加到多个列表中?

而不是

x, y, z = (1, 2, 3)
x_list.append(x)
y_list.append(y)
z_list.append(z)

这能否在一行内完成?
x_list, y_list, z_list ~ (1, 2, 3)

x_list[x_list.append(0) or -1], y_list[y_list.append(0) or -1], z_list[z_list.append(0) or -1] = (1, 2, 3) :-Px_list[x_list.append(0) or -1], y_list[y_list.append(0) or -1], z_list[z_list.append(0) or -1] = (1, 2, 3) :-P - Stefan Pochmann
顺便说一句,实际上可能有更好的方法来实现你想做的事情... - Stefan Pochmann
4个回答

6
你可以这样做。
>>> t = (1,2,3)
>>> x,y,z = [1,2,3],[4,5,6],[7,8,9]

>>> x[len(x):],y[len(y):],z[len(z):] = tuple(zip(t))
>>> x
>>> [1,2,3,1]
>>> y
>>> [4,5,6,2]
>>> z
>>> [7,8,9,3]

如果您希望在开头插入,可以执行以下操作:

>>> x[:0],y[:0],z[:0] = tuple(zip(t))

1
元组(zip(...))技巧很好。但是在切片中+1是不必要的。 - Olivier Melançon

4

要轻松实现这一点并不容易,至少不会没有任何代价。

但是您可以使用循环来为代码提供一些结构。

for lst, j in [(x_list, x), (y_list, y), (z_list, z)]:
    lst.append(j)

另一种处理方式如下:

lst = (x_list, y_list, z_list)
num = (1, 2, 3)

for i, j in zip(lst, num):
    i.append(j)

3
你可以进一步使用zip((x_list,y_list,z_list),t)代替[(x_list,x),(y_list,y),(z_list,z)],其中t是原始元组。 - DYZ

3

我认为并没有一种官方的方法,但假设你有列表 l1, l2l3,你可以这样做。

l1[len(l1):], l2[len(l2):], l3[len(l3):] = [1], [2], [3]

这更接近于extend的行为,而不是append

如果你不喜欢这种方法,你也可以使用zip和一个for循环来实现单行。

for l, el in zip((l1, l2, l3), (x, y, z)): l.append(el)

我认为第一种方式最接近我想要的,虽然map可能更符合我的意图。谢谢你的答案。它和@Bro-grammer的答案相似。不过我想他的回答更早?谢谢! - ZAR
1
他的是第一个,但索引错误了,不过因为这已经被纠正了,我建议你给他以荣誉。 - Olivier Melançon

1

根据您的初始输入,您可以在列表上映射一个函数,将每个元素转换为列表,然后执行解包操作:

x, y, z = map(lambda x:[x], (1, 2, 3))

这将覆盖列表中现有的内容。 - Sohaib Farooqi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接