Create Rank of tuples in python
How do i do this? starting with this sample
Id, Id2 CCC
[ (A123 A120 '2011-03'),
LL= (A133 A123 '2011-03'),
( D123 D120 '2011-04'),
(D140 D123 '2011-04'),]
I.m trying to get this, Adding rank to each tuple.
[(A123, A120 ,'2011-03',1),
LL= (A133, A开发者_JS百科123, '2011-03',2),
( D123, D120, '2011-04',3),
(D140, D123, '2011-04',4),]
for i in range(len(LL)):
RowId = i+1
LL.append(RowId)
I get something like this:
[(A123, A120 ,'2011-03'),
LL= (A133, A123, '2011-03),
( D123, D120, '2011-04),
(D140, D123, '2011-04),1,2,3,4]
import pprint
LL= [ ('A123', 'A120', '2011-03'),
('A133', 'A123', '2011-03'),
('D123', 'D120', '2011-04'),
('D140', 'D123', '2011-04'),]
LL = [row+(i,) for i,row in enumerate(LL,1)]
pprint.pprint(LL)
yields
[('A123', 'A120', '2011-03', 1),
('A133', 'A123', '2011-03', 2),
('D123', 'D120', '2011-04', 3),
('D140', 'D123', '2011-04', 4)]
Here's a bit of explanation:
We start with LL
defined like this:
In [28]: LL
Out[28]:
[('A123', 'A120', '2011-03'),
('A133', 'A123', '2011-03'),
('D123', 'D120', '2011-04'),
('D140', 'D123', '2011-04')]
The first trick is to use enumerate:
In [30]: list(enumerate(LL))
Out[30]:
[(0, ('A123', 'A120', '2011-03')),
(1, ('A133', 'A123', '2011-03')),
(2, ('D123', 'D120', '2011-04')),
(3, ('D140', 'D123', '2011-04'))]
which is close to what you want, except that the "rank" starts counting at 0, and is placed in front of the row instead of at the end. We can tell enumerate
to start counting with 1, using enumerate(LL,1)
, and we can place the rank at the end of the row using a list comprehension:
In [31]: [row+(i,) for i,row in enumerate(LL,1)]
Out[31]:
[('A123', 'A120', '2011-03', 1),
('A133', 'A123', '2011-03', 2),
('D123', 'D120', '2011-04', 3),
('D140', 'D123', '2011-04', 4)]
In the list comprehension, row
is a tuple like ('A123', 'A120', '2011-03')
,
and row+(i,)
is a sum of tuples:
In [32]: ('A123', 'A120', '2011-03')+(1,)
Out[32]: ('A123', 'A120', '2011-03', 1)
This is how each row of the list comprehension is constructed.
You can use enumerate to create rank variables(added 1 for starting from 1), and create a new list of new tuples, because tuples are immutable, thats why we are creating new tuples.
Example, should work on your list too:
In [1]: LL=[(1,2,3),(1,2,3)]
In [2]: [j+(i+1,) for i,j in enumerate(LL)]
Out[2]: [(1, 2, 3, 1), (1, 2, 3, 2)]
for i in range(len(LL)): RowId = i+1 LL[i].append(RowId)
Please test it.
精彩评论