将新元组加入到 Python 中的第一个元组列表中
我是 python 新手,不知道该怎么做。
我有一个代表数据的元组列表和另一个代表标题的列表。 我需要将一组组合放入新元组中才能从中查看。
data = [( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')]
header = ["ID", "MyData"]
请帮忙
newdata = [("ID", "MyData"),( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')]
。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里:
请注意,这将就地修改
data
。您无需修改数据即可获得相同的结果,如下所示:Here:
Note that this will modify
data
in-place. You can achieve the same results without modifying data like so:创建一个全新的值,没有任何临时值:
添加两个列表将它们连接起来。我们将作为列表的标题转换为元组(因为我们希望最终结果中包含其数据的元组),然后创建一个包含它的列表,以便我们可以将两个列表粘合在一起。
Creating a completely new value, without any temporaries:
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