简体   繁体   English

为什么带星号的赋值生成列表而不是元组?

[英]Why does starred assignment produce lists and not tuples?

In python, I can write something like this:在python中,我可以写这样的东西:

some_list = [(1, 2, 3), (3, 2, 1)]

for i, *args in some_list:
   print(args)

I will get the next output:我会得到下一个输出:

[2, 3]
[2, 1]

When we use *args as function arguments, it is unpacked into a tuple .当我们使用*args作为函数参数时,它被解包成一个tuple

Why do we receive a list in this situation?为什么在这种情况下我们会收到一份list

It is just a design decision.这只是一个设计决定。 Making it a tuple was debated in the PEP 3132 , but rejected on usability grounds:PEP 3132中对将其tuple进行了辩论,但以可用性为由予以拒绝:

Make the starred target a tuple instead of a list.使加星标的目标成为元组而不是列表。 This would be consistent with a function's *args, but make further processing of the result harder.这将与函数的 *args 一致,但会使结果的进一步处理更加困难。

Simlarly, making it of the same type as the iterable on the rhs of the assignment, was rejected:同样,使其与赋值的 rhs 上的可迭代类型相同,也被拒绝:

Try to give the starred target the same type as the source iterable, for example, b in a, *b = 'hello' would be assigned the string 'ello'.尝试为加星标的目标提供与源可迭代对象相同的类型,例如,a 中的 b,*b = 'hello' 将被分配字符串 'ello'。 This may seem nice, but is impossible to get right consistently with all iterables.这可能看起来不错,但不可能与所有可迭代对象保持一致。

The very example of yours is listed in the same PEP under specification .您的示例列在规范下的同一 PEP 中。

Some reasoning is found in the mailing list of that debate.在该辩论的邮件列表中可以找到一些推理。

When dealing with an iterator, you don't know the length in advance, so the only way to get a tuple would be to produce a list first and then create a tuple from it.在处理迭代器时,您事先不知道长度,因此获取元组的唯一方法是先生成一个列表,然后从中创建一个元组。

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

相关问题 为什么Django使用元组设置而不是列表? - Why does Django use tuples for settings and not lists? 为什么此代码会产生列表列表? - Why Does This Code Produce a List of Lists? 为什么变量赋值在列表中如此工作? - Why does variable assignment work like this in lists? 为什么创建列表列表会产生意外行为? - Why does creating a list of lists produce unexpected behavior? 解析字典列表、嵌套列表和元组以生成新列表 - parsing a list of dictionaries, nested lists and tuples to produce a new list 为什么不打印没有重复元组的元组列表? - Why does it not print a list of tuples with no repeated tuples? 为什么Python将元组,列表,集合和字典视为根本不同的东西? - Why does Python treat tuples, lists, sets and dictionaries as fundamentally different things? Python 2 如何比较字符串和整数? 为什么列表比数字大,元组比列表大? - How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists? 为什么 numpy 需要元组列表而不是列表列表? - Why numpy requires list of tuples and not list of lists? 列表用于同类数据,元组用于异构数据......为什么? - Lists are for homogeneous data and tuples are for heterogeneous data… why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM