简体   繁体   中英

Unpack parts of a tuple into tuple

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.

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.

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

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.

If you always want to have first 6 values in new tuple:

t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')
newT = t[0:6]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM