任意可迭代对象都可以进行解包操作
原则: 赋值变量的个数和可迭代对象的个数保持一致
字符串
name = ‘wangys‘ a, b, c, d, e, f = name print(a) print(b) print(c) print(d) print(e) print(f) w a n g y s
元组
info = (‘wangys‘, 30, (1990, 10, 19)) name, age, date = info print(name) print(age) print(date) name, age, (year, mon, day) = info print(year) print(mon) print(day) wangys 30 (1990, 10, 19) 1990 10 19
只取所需时,如果我们知道可迭代对象的个数,可以使用一个之前没有定义过的变量站位
info = (‘wangys‘, 30, (1990, 10, 19)) _, age, _ = info print(age) 30
可以使用*变量名来解压多个值
info = ‘sunachr-prod:x:1003:1003::/home/sunachr-prod:/bin/bash‘ name, *fields, homedir, sh = info.split(‘:‘) print(name) print(homedir) print(sh) print(fields) sunachr-prod /home/sunachr-prod /bin/bash [‘x‘, ‘1003‘, ‘1003‘, ‘‘] info = ‘sunachr-prod:x:1003:1003::/home/sunachr-prod:/bin/bash‘ name, *_, homedir, sh = info.split(‘:‘) print(name) print(homedir) print(sh) sunachr-prod /home/sunachr-prod /bin/bash
原文:https://www.cnblogs.com/wc89/p/12658525.html