简体   繁体   中英

join new tuple to first list of tuples in Python

I am newbie to python and don't know how to do this.

I have a list of tuples which represent data and another list which represents header. I need a set of combinations into new tuples to look from this.

data = [( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')]
header = ["ID", "MyData"]

into this

newdata = [("ID", "MyData"),( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')]

please help.

Here:

data.insert(0, tuple(header))

Note that this will modify data in-place. You can achieve the same results without modifying data like so:

newdata = [tuple(header)]
newdata.extend(data)

Creating a completely new value, without any temporaries:

[tuple(header)] + data

Addition of two lists concatenates them. We turn the header, which is a list, into a tuple (since we want a tuple of its data in the final result), and then make a list that contains it, so that we can glue the two lists together.

This should do it

data.insert(0,tuple(header))
newdata = data

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