在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)
在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)
>>> 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))
要轻松实现这一点并不容易,至少不会没有任何代价。
但是您可以使用循环来为代码提供一些结构。
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)
zip((x_list,y_list,z_list),t)
代替[(x_list,x),(y_list,y),(z_list,z)]
,其中t
是原始元组。 - DYZ我认为并没有一种官方的方法,但假设你有列表 l1
, l2
和 l3
,你可以这样做。
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)
根据您的初始输入,您可以在列表上映射一个函数,将每个元素转换为列表,然后执行解包操作:
x, y, z = map(lambda x:[x], (1, 2, 3))