gpt4 book ai didi

python - 多字符串变量声明python

转载 作者:太空狗 更新时间:2023-10-30 02:26:47 24 4
gpt4 key购买 nike

我想弄清楚这段代码的作用:

printdead, printlive = '_#'

它来自这里,一个实现了初等元胞自动机的网站:https://rosettacode.org/wiki/One-dimensional_cellular_automata#Python

显然我可以通过简单地写来替换上面的语句

printdead = '_'
printlive = '#'

printdead = '_'; printlive = '#'

printdead, printlive = '_', '#'

这对我来说完全没问题。但是第一个语句是如何工作的?

最佳答案

这称为可迭代拆包。如果赋值的右侧是一个可迭代对象,您可以将这些值解包为不同的名称。字符串、列表和元组只是 Python 中可迭代对象的几个例子。

>>> a, b, c = '123'
>>> a, b, c
('1', '2', '3')
>>> a, b, c = [1, 2, 3]
>>> a, b, c
(1, 2, 3)
>>> a, b, c = (1, 2, 3)
>>> a, b, c
(1, 2, 3)

如果您使用的是 Python 3,您可以访问 Extended Iterable Unpacking这允许您在作业中使用一个通配符。

>>> a, *b, c = 'test123'
>>> a, b, c
('t', ['e', 's', 't', '1', '2'], '3')
>>> head, *tail = 'test123'
>>> head
't'
>>> tail
['e', 's', 't', '1', '2', '3']

关于python - 多字符串变量声明python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com