gpt4 book ai didi

Python:在元组列表中插入计数

转载 作者:太空宇宙 更新时间:2023-11-04 08:16:47 24 4
gpt4 key购买 nike

我正在尝试在元组列表中插入“计数”(从 0 开始)。我有这样的东西:

list = [(1, 'Cat', 200, 3.2), (4, 'Dog', 204, 4.1), (2, 'Rabbit', 519, 2.0)]

我希望它是这样的:

list = [(1, 'Cat', 200, 0, 3.2), (4, 'Dog', 204, 1, 4.1), (2, 'Rabbit', 519, 2, 2.0)]

我试过这样的:

>>> i = 0
>>> for line in list:
... list.insert(-2,i)
... i+=1
... print list

但它会在元组之间插入所有计数,这不是我想要的。任何人都可以帮助 Python 初学者解决这个问题吗?谢谢!

最佳答案

In [11]: lis=[(1, 'Cat', 200, 3.2), (4, 'Dog', 204, 4.1), (2, 'Rabbit', 519, 2.0)]

In [12]: lis=map(list,lis) #convert tuples to list


In [13]: lis #now lis is list of lists instead of list of tuples
Out[13]:
[[1, 'Cat', 200, 3.2000000000000002],
[4, 'Dog', 204, 4.0999999999999996],
[2, 'Rabbit', 519, 2.0]]

#use enumerate() for indexes, no need of manual indexing

In [14]: for i,x in enumerate(lis):
x.insert(-1,i) #insert at -1 not -2
....:
....:

In [15]: lis
Out[15]:
[[1, 'Cat', 200, 0, 3.2000000000000002],
[4, 'Dog', 204, 1, 4.0999999999999996],
[2, 'Rabbit', 519, 2, 2.0]]

关于Python:在元组列表中插入计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13038963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com