在 python 中创建元组的排名
我该怎么做? 从这个示例开始,
Id, Id2 CCC
[ (A123 A120 '2011-03'),
LL= (A133 A123 '2011-03'),
( D123 D120 '2011-04'),
(D140 D123 '2011-04'),]
我试图得到这个,为每个元组添加排名。
[(A123, A120 ,'2011-03',1),
LL= (A133, A123, '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)
我得到这样的东西:
[(A123, A120 ,'2011-03'),
LL= (A133, A123, '2011-03),
( D123, D120, '2011-04),
(D140, D123, '2011-04),1,2,3,4]
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, A123, '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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有
一些解释:
我们从这样定义的
LL
开始:第一个技巧是使用 enumerate:
这与您想要的很接近,只是“排名”从 0 开始计数,并且放置在行的前面而不是末尾。我们可以使用
enumerate(LL,1)
告诉enumerate
从 1 开始计数,并且我们可以使用 列表理解:在列表理解中,
row
是一个元组喜欢('A123', 'A120', '2011-03')
,row+(i,) 是元组之和:
这就是列表推导式的每一行的构造方式。
yields
Here's a bit of explanation:
We start with
LL
defined like this:The first trick is to use enumerate:
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, usingenumerate(LL,1)
, and we can place the rank at the end of the row using a list comprehension:In the list comprehension,
row
is a tuple like('A123', 'A120', '2011-03')
,and
row+(i,)
is a sum of tuples:This is how each row of the list comprehension is constructed.
您可以使用 enumerate 创建排名变量(从 1 开始添加 1),并创建新元组的新列表,因为元组是不可变的,这就是我们创建新元组的原因。
例如,也应该适用于您的列表:
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:
请测试一下。
Please test it.