我有這樣拆開零件成元組
t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')
的元組和我要提取的前6個值作爲元組(按順序),最後值作爲字符串。
下面的代碼已經可以工作了,但我想知道是否有一個「單行」來實現我在找的東西。
# works, but it's not nice to unpack each value individually
cid,sc,ma,comp,mat,step,alt = t
t_new = (cid,sc,ma,comp,mat,step,)
print(t_new, alt) # (1, '0076', 'AU', '9927016803A', '9927013903B', '0010') VO
這是非常接近我正在尋找,但它返回的第一個值的列表,而不是一個元組:
# works, but returns list
*t_new,alt = t
print(t_new, alt) # [1, '0076', 'AU', '9927016803A', '9927013903B', '0010'] VO
我已經試過以下,但瓦特/ o成功:
tuple(*t_new),alt = t # SyntaxError
(*t_new),alt = t # still a list
(*t_new,),alt = t # ValueError
如果沒有其他辦法,我可能會去我的第二次嘗試,並將列表投給一個元組。
它永遠不會發生,我認爲我可以切片的元組和列表一樣。這是我正在尋找的一個班輪。 –