gpt4 book ai didi

python - 将元组的一部分解包为元组

转载 作者:行者123 更新时间:2023-11-28 20:36:42 24 4
gpt4 key购买 nike

我有一个这样的元组

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

我已经尝试过以下方法,但没有成功:

tuple(*t_new),alt = t # SyntaxError
(*t_new),alt = t # still a list
(*t_new,),alt = t # ValueError

如果没有其他办法,我可能会进行第二次尝试并将列表转换为元组。

最佳答案

为什么不只是:

t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')

t_new, alt = t[:-1], t[-1]
print(t_new, alt) # (1, '0076', 'AU', '9927016803A', '9927013903B', '0010') VO

关于python - 将元组的一部分解包为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44672106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com