时间:2022-02-28 09:21:36 | 栏目:Python代码 | 点击:次
现在有一个包含N个元素的可迭代对象,怎样把它里面的元素解压后同时赋值给N个变量?怎样同时赋值给M个变量(M<N)?
p = [4, 5] 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
record = ('ACME', 50, 123.45, (12, 18, 2012)) name, *_, (*_, year) = record print(name, year)
"""
输出结果:
ACME 2012
"""
records = [ ('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
"""
line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false' uname, *field, homedir, sh = line.split(':') print(uname, homedir, sh)
"""
输出结果:
nobody /var/empty /usr/bin/false
"""