简体   繁体   English

将列表与元组列表中元组的第一项合并

[英]Merge list with first item of tuple that is in a list of tuples

I want to merge list1 with another list2, that consists of tuples with two items.我想将 list1 与另一个 list2 合并,后者由具有两个项目的元组组成。 But I only want to get the first items of the tuples merged with list1.但我只想将元组的第一项与 list1 合并。 Here is an example how list2 can look like:以下是 list2 的示例:

[('x1', 0), ('x2', 1), ('x3', 2), ('x4', 3), ('x5', 4), ('x6', 5), ('x7', 6), ('x8', 7), ('x9', 8), ('x10', 9), ('x11', 10)]

I want to add all the x to list1.我想将所有 x 添加到 list1。 List1 looks like this List1 看起来像这样

["randomString"]

Is there any other way, except that I am looping over all the first elements of list2, save the result in another new created list and just add it to list1?除了我循环遍历 list2 的所有第一个元素,将结果保存在另一个新创建的列表中并将其添加到 list1 之外,还有其他方法吗?

Is there any other way, except that I am looping over all the first elements of list2除了我循环遍历 list2 的所有第一个元素之外,还有其他方法吗

In general, no.一般来说,没有。 In order to collect the items from that list, you need to iterate over it.为了从该列表中收集项目,您需要对其进行迭代。 Of course, instead of saving it in an intermediary list, you could just add them to the target list directly:当然,您可以直接将它们添加到目标列表中,而不是将其保存在中间列表中:

>>> list2 = [('x1', 0), ('x2', 1), ('x3', 2), ('x4', 3), ('x5', 4), ('x6', 5), ('x7', 6), ('x8', 7), ('x9', 8), ('x10', 9), ('x11', 10)]
>>> list1 = ['randomString']
>>> for x, n in list2:
        list1.append(x)

>>> list1
['randomString', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM