问题描述
现在有一个包含N个元素的可迭代对象,怎样把它里面的元素解压后同时赋值给N个变量?怎样同时赋值给M个变量(M<N)?
解决方案
x, y = p
print(x, y)
# 输出结果:4 5
data = [\'Test\', 1, 3.14, (2021, 12, 1)]
a, b, c, d = data
print(a, b, c, d)
# 输出结果:Test 1 3.14 (2021, 12, 1)
a, b, c, (year, month, day) = data
print(a, b, c, year, month, day)
# 输出结果:Test 1 3.14 2021 12 1
当变量的个数少于可迭代对象元素的个数时,程序会抛出ValueError。这时,可以用Python的星号表达式来解决。data = [1, 2, 3, 4, 5]
a, b, *c, d = data
print(a, b, c, d)
# 输出结果:1 2 [3, 4] 5
需要注意的是上面解压出的c变量永远是list类型,不管c的元素有几个(包括0个)。
总结
迭代解压语法的几个应用场景:
比如:s = \'hello\'
a, b, c, d, e = s
print(a, b, c, d, e)
# 输出结果:h e l l o
name, *_, (*_, year) = record
print(name, year)
\"\"\"
输出结果:
ACME 2012
\"\"\"
(\'foo\', 1, 2),
(\'bar\', \'hello\'),
(\'foo\', 3, 4),
]
def print_foo(x, y):
print(\'foo\', x, y)
def print_bar(s):
print(\'bar\', s)
for tag, *args in records:
if tag == \'foo\':
print_foo(*args)
elif tag == \'bar\':
print_bar(*args)
\"\"\"
输出结果:
foo 1 2
bar hello
foo 3 4
\"\"\"
uname, *field, homedir, sh = line.split(\':\')
print(uname, homedir, sh)
\"\"\"
输出结果:
nobody /var/empty /usr/bin/false
\"\"\"
来源:https://www.cnblogs.com/L999C/p/15630509.html
图文来源于网络,如有侵权请联系删除。