Python解包运算符(*) [英] Python unpacking operator (*)

查看:330
本文介绍了Python解包运算符(*)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 python codegolf ,看到有人以一种奇怪的方式使用拆包运算符:

I was researching about python codegolf and saw someone use the unpacking operator in a strange way:

*s,='abcde'

我知道拆包运算符基本上是对一个序列进行迭代.所以我知道

I know that the unpacking operator basically iterates over a sequence. So I know that

s=[*'abcde']

将解压缩" abcde字符串并将['a', 'b', 'c', 'd', 'e']保存在变量s中.

will "unpack" the abcde string and save ['a', 'b', 'c', 'd', 'e'] in variable s.

有人可以尽可能详尽地解释

Can someone explain as thoroughly as possible how does the

*s,='abcde'

陈述工作?我知道它的作用与s=[*'abcde']相同,但是它以不同的方式完成它.为什么将解包迭代器放在变量而不是字符串上?为什么变量名后面会出现逗号?

statement work? I know it does the same thing as s=[*'abcde'] but it accomplishes it in a different way. Why is the unpacking iterator on the variable, instead of the string? Why is there a comma right after the variable name?

推荐答案

这是 Iterable开箱.您可能已经在其他地方看到过,它可以从单个表达式为多个变量赋值

This is Iterable Unpacking. You may have seen it in other places to assign values to multiple variables from a single expression

a, b, c = [1, 2, 3]

此语法包含*,以指示此变量应为包含未明确分配给另一个变量的可迭代元素的列表.

This syntax includes a * to indicate that this variable should be a list containing the elements from the iterable that weren't explicitly assigned to another variable.

a, *b, c = [1, 2, 3, 4, 5]
print(b)
# [2, 3, 4]

那么,您的示例中发生了什么?仅分配了一个变量名,因此它将采用所有未分配给另一个变量的项目,在这种情况下,它们都是全部.如果您只是尝试

So, what's going on in your example? There's only a single variable name being assigned to, so it's going to take all the items not assigned to another variable, which in this case is all of them. If you try just

*s='abcde'

您会得到

SyntaxError: starred assignment target must be in a list or tuple

这就是为什么要使用逗号的原因,因为结尾逗号是表示单值元组的原因.

Which is why that comma is there, as a trailing comma is how you indicate a single-value tuple.

这篇关于Python解包运算符(*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆