开发者

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", "MyD开发者_如何学Goata"),( 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜