I have a tuple like this
我有这样的元组
t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')
and I want to extract the first 6 values as tuple (in order) and the last value as a string.
我想将前6个值提取为元组(按顺序),将最后一个值提取为字符串。
The following code already works, but I am wondering if there is a "one-liner" to achieve what I'm looking for.
以下代码已经有效,但我想知道是否有一个“单行”来实现我正在寻找的东西。
# 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
This is very close to what I'm looking for, but it returns the first values as a list instead of a tuple:
这非常接近我正在寻找的东西,但它将第一个值作为列表而不是元组返回:
# works, but returns list
*t_new,alt = t
print(t_new, alt) # [1, '0076', 'AU', '9927016803A', '9927013903B', '0010'] VO
I've already tried the following, but w/o success:
我已经尝试了以下内容,但没有成功:
tuple(*t_new),alt = t # SyntaxError
(*t_new),alt = t # still a list
(*t_new,),alt = t # ValueError
If there's no other way, I will probably go with my second attempt and cast the list to a tuple.
如果没有其他方法,我可能会进行第二次尝试并将列表转换为元组。
3 个解决方案
#1
4
why not just:
为什么不呢:
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
#2
2
Either just convert it to a tuple again like you said:
要么就像你说的那样再把它转换成一个元组:
*t_new, alt = t
t_new = tuple(t_new)
Or just use slicing:
或者只使用切片:
t_new = t[:-1] # Will be a tuple
alt = t[-1]
If you want to talk about efficiency, tuple packing / unpacking is relatively slow when compared with slicing, so the bottom one should be the fastest.
如果你想谈论效率,与切片相比,元组打包/解包相对较慢,所以底部应该是最快的。
#3
1
If you always want to have first 6 values in new tuple:
如果您总是希望在新元组中有前6个值:
t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')
newT = t[0:6]
#1
4
why not just:
为什么不呢:
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
#2
2
Either just convert it to a tuple again like you said:
要么就像你说的那样再把它转换成一个元组:
*t_new, alt = t
t_new = tuple(t_new)
Or just use slicing:
或者只使用切片:
t_new = t[:-1] # Will be a tuple
alt = t[-1]
If you want to talk about efficiency, tuple packing / unpacking is relatively slow when compared with slicing, so the bottom one should be the fastest.
如果你想谈论效率,与切片相比,元组打包/解包相对较慢,所以底部应该是最快的。
#3
1
If you always want to have first 6 values in new tuple:
如果您总是希望在新元组中有前6个值:
t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')
newT = t[0:6]