简体   繁体   中英

Python - List comprehension with tuple unpack

I have a list of tuples like: tuple_list = [ (0,1,2), (3,4,5), (6,7,8) ]

I need to create a list where each tuple is converted into a list with other static items added eg:

new_list = [ [var1, var2, unpack(t)] for t in tuple_list ]

How would I accomplish this in python?

If your tuple is not too long, you can do:

[var1, var2, k, v, r for (k, v, r) in youList]

otherwise, write a function:

def myPack(*arg):
    return list(arg)
[myPack(var1, var2, *I) for I in youList]
new_list = [ [var1, var2] + list(t) for t in tuple_list ]
new_list = [ [var1, var2] + [val for val in t] for t in tuple_list]
// => [[var1, var2, 0, 1, 2], [var1, var2, 3, 4, 5], [var1, var2, 6, 7, 8]]

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