简体   繁体   中英

Add consecutive numbering to list of tuples

i have lists which look like:

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

and what I'm trying to get should look like:

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

You can use enumerate to pack them into 2-tuples, and then map them back into one tuple:

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

First object in the enumerate will be:

(1, ('A', 'B', 'C'))

We turn the number into a 1-tuple, map it into a string and then add the original tuple to it.

EDIT: Some different methods with time added

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

Use a list comprehension with unpacking.

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

It's also quite fast.

In [3]: %timeit([(str(i), *j) for i, j in enumerate(t, start=1)])
100000 loops, best of 3: 5.91 µs per loop

This does not work in Python <3.5. This behavior was introduced in PEP 448 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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