简体   繁体   English

如何使用长度可变的序列解包?

[英]How to use sequence unpacking with a sequence of variable length?

If I know the length of a list in advance, I can use sequence unpacking to assign variable the elements of the list thus: 如果我事先知道列表的长度,则可以使用序列拆包为变量分配列表的元素,从而:

my_list = [1,2,3]

x, y, z = my_list

If I don't know the length of the list in advance, how can I assign variables to the elements of the list using sequence unpacking? 如果我事先不知道列表的长度,如何使用序列解包将变量分配给列表的元素? If for argument's sake I don't care how the variables are named, can I first get the length of the list and then unpack to this amount of arbitrarily-named variables? 如果出于争论的目的,我不在乎变量的命名方式,那么我可以先获取列表的长度,然后再解压缩为任意数量的变量吗?

Certainly not recommend but possible: 当然建议,但可能:

my_list = [1, 2, 3]
for counter, value in enumerate(my_list):
    exec 'a{} = {}'.format(counter, value)
print a0, a1, a2

Output: 输出:

1 2 3

Or use Python 3: 或使用Python 3:

>>> a, *rest = my_list
>>> a
1
>>> rest
[2, 3]

you can force the length of the list to unpacking to the size you want like this 您可以像这样将列表的长度强制解压缩为所需的大小

>>> my_list=range(10)
>>> a,b,c = my_list[:3]
>>> a
0
>>> b
1
>>> c
2
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

if they are less you get a error, otherwise you take the 3 first elements 如果它们较小,您将得到一个错误,否则,您将获得前三个要素

to the case of less elements you can do something like this 对于较少元素的情况,您可以执行以下操作

>>> my_list=[1,2]
>>> x,y,z=(my_list[:3] +[-1]*3)[:3]
>>> x
1
>>> y
2
>>> z
-1
>>> 

have a list with default values that you concatenate to the sub-list of my_list and from the result you take what you need 有一个默认值的列表,您可以将其连接到my_list的子列表,然后从结果中获取所需的内容

The right answer is that you should leave these elements in a list. 正确的答案是您应该将这些元素保留在列表中。 This is what a list is for. 这就是列表的用途。

The wrong answer is to add local variables in a roundabout way. 错误的答案是以回旋方式添加局部变量。 For Python 3: 对于Python 3:

ctr = 0
for value in my_list:
    __builtins__.locals()['my_list_{}'.format(ctr)] = value
    ctr += 1

If my_list has n items, this will create variables my_list_0, my_list_1, ..., my_list_{n-1} . 如果my_list具有n项目,则将创建变量my_list_0, my_list_1, ..., my_list_{n-1}

Please don't do this. 请不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM