gpt4 book ai didi

python - 多目标分配

转载 作者:太空宇宙 更新时间:2023-11-04 07:09:15 24 4
gpt4 key购买 nike

我正在阅读一本关于 Python 的书,书中有一个关于多目标分配的特殊部分。现在这本书是这样解释的:

enter image description here

但我没有看到它的用途。这对我来说毫无意义。为什么要使用更多变量?有理由这样做吗?这与使用 a='spam' 然后打印 3 次 a 有何不同?

我只能想到用它来清空一行中的变量。

最佳答案

多重赋值的一个很好的用途是将一堆变量设置为相同的数字。

下面是一个演示:

>>> vowels = consonants = total = 0
>>> mystr = "abcdefghi"
>>> for char in mystr:
... if char in "aeiou":
... vowels += 1
... elif char in "bcdfghjklmnpqrstvwxyz":
... consonants += 1
... total += 1
...
>>> print "Vowels: {}\nConsonants: {}\nTotal: {}".format(vowels, consonants, total)
Vowels: 3
Consonants: 6
Total: 9
>>>

如果没有多重赋值,我必须这样做:

>>> vowels = 0
>>> consonants = 0
>>> total = 0

如您所见,这要冗长得多。

总而言之,多重赋值只是 Python 语法糖,让事情变得更简单/更清晰。

关于python - 多目标分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20523387/

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