![](/img/trans.png)
[英]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.