简体   繁体   中英

Create a tuple from a variable and a list

I have a variable s which is a string, and a list of ints called l . What is the quickest way to add s to the front of l and convert the end result of that concatenation into a tuple?

This is working for me:

l.insert(0, s)
t = tuple(l)

Is there a better way?

Concatenate them:

t = (s,) + tuple(l)

Insertion in front of the list would alter the list itself, and requires looping over the whole list twice (once for insertion, moving the rest of the list up 1 step, once for creating the tuple).

使用生成器表达式构造结果,该表达式一次遍历列表,并且不需要最终串联:

t = tuple(l[i] if i > -1 else s for i in xrange(-1, len(l)))

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