【问题标题】:What is this type of variable assignment in Python? [duplicate]Python中这种类型的变量赋值是什么? [复制]
【发布时间】:2019-12-03 03:48:31
【问题描述】:

我在 Python 中多次看到这种语法,但不知道它的真正含义

这是一个例子:

foo, bar = baz

谁能给我解释一下?

【问题讨论】:

标签: python


【解决方案1】:

它在一个可迭代对象中解包多个项目。比如

foo, bar = ['thing1', 'thing2']
print(foo)
print(bar)

会输出

thing1
thing2

所以如果我们改为:

packed_items = ['thing1', 'thing2']
foo, bar = packed_items
print(foo)
print(bar)

我们会得到同样的结果。

另一个需要了解的重要语法是* 运算符。

它可用于在打开包装时抓取任意数量的物品并将它们放入列表中。

例如:

packed_items = ['thing1', 'thing2', 'thing3', 'thing4', 'thing5']
foo, *middle, bar = packed_items
print(foo, middle, bar)

收益thing1 ['thing2', 'thing3', 'thing4'] thing5

而

foo, middle, *bar = packed_items
print(foo, middle, bar)

将产生thing1 thing2 ['thing3', 'thing4', 'thing5']

最后,注意* 操作符可以返回一个空白列表

packed_items = ['thing1', 'thing2']
foo, middle, *bar = packed_items
print(foo, middle, bar)

产生thing1 thing2 [],而不是因为没有足够的参数来解包而给你一个错误。

【讨论】:

    【解决方案2】:

    它用于将一个可迭代变量拆分为多个变量。所以如果 baz = [1, 2], foo = 1 和 bar = 2。称为“解构”。

    【讨论】:

      【解决方案3】:

      一张图片胜过一千个字

      【讨论】:

      • 对于失明且需要使用屏幕阅读器的 StackOverflow 用户来说,一张图片的价值不超过一千字。您没有理由不能自己输入并格式化它以使其看起来相同
      • 案件的道歉
      • 这是什么意思?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多