[英]Add elements from list of tuples to new list if consecutive tuples share the same first element
[英]Add consecutive numbering to list of tuples
我有看起来像这样的列表:
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]
而我想要得到的应该是这样的:
[('1', 'A', 'B', 'C'), ('2', 'D', 'E', 'F'), ('3', 'G', 'H', 'I')]
您可以使用枚举将它们打包成2个元组,然后将它们映射回一个元组:
my_list = [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]
new_list = [(str(x[0]),)+x[1] for x in enumerate(my_list, start=1)]
枚举中的第一个对象是:
(1, ('A', 'B', 'C'))
我们将数字转换为1元组,将其映射为字符串,然后将原始元组添加到其中。
编辑:添加时间的一些不同方法
my_list = [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]*1000
new_list = [(str(x[0]+1),)+x[1] for x in enumerate(my_list)]
## 1000 loops, best of 3: 815 µs per loop
new_list = [(str(x[0]),)+x[1] for x in enumerate(my_list, start=1)]
## 1000 loops, best of 3: 766 µs per loop, by schwobaseggl
new_list = map(lambda x:(str(x[0]),)+x[1],enumerate(my_list, start=1))
## 1000 loops, best of 3: 989 µs per loop
new_list = [(str(index),)+values for index, values in enumerate(my_list, start=1)]
## 1000 loops, best of 3: 669 µs per loop, by Donkey Kong
使用列表理解和解包。
In [1]: t = [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]
In [2]: [(str(i), *j) for i, j in enumerate(t, start=1)]
Out[2]: [('1', 'A', 'B', 'C'), ('2', 'D', 'E', 'F'), ('3', 'G', 'H', 'I')]
它也相当快。
In [3]: %timeit([(str(i), *j) for i, j in enumerate(t, start=1)])
100000 loops, best of 3: 5.91 µs per loop
在Python <3.5中不起作用。 PEP 448中引入了此行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.