将连续编号添加到元组列表中

时间:2016-06-05 17:04:25

标签: python python-3.x

我的列表看起来像:

[('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I')]

我想要得到的应该是:

[('1', 'A', 'B', 'C'), ('2', 'D', 'E', 'F'), ('3', 'G', 'H', 'I')]

2 个答案:

答案 0 :(得分:2)

您可以使用枚举将它们打包成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

答案 1 :(得分:1)

将列表理解与解包一起使用。

Boolean

它也很快。

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')]

这在Python< 3.5中不起作用。此行为是在PEP 448中引入的。

相关问题