[英]Extended unpacking not creating separate items in list
我正在執行以下代碼:
s = 'python'
a, b, *c, d = s[0], s[1], s[2:-1], s[-1]
print(c)
我將 output 作為['tho']
請幫助我理解為什么 output 不是['t', 'h', 'o']
?
因為我們在 LHS 上使用* operator
,所以 output 應該是['t', 'h', 'o']
而不是['tho']
您還需要解壓縮字符串,否則只有一個元素( 'tho'
):
s = 'python'
a, b, *c, d = s[0], s[1], *s[2:-1], s[-1]
print(c)
Output: ['t', 'h', 'o']
我這你正在尋找的是:
a,b,*c,d = s
print(c)
拆包真正有意義的地方
這是因為s[2:-1]
沒有解包。 沒有理由拆包。
你需要:
a, b, *c, d = s[0], s[1], *s[2:-1], s[-1]
解包分配只會在有多個非附加值時解包為一個多個值序列,例如't', 'h', 'o'
,而不是當值為'tho'
時。
現在:
print(c)
是:
['t', 'h', 'o']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.