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

标签 python list insert count tuples

我正在尝试在元组列表中插入“计数”(从 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/

相关文章:

c# - System.Collections.Generic.List 中的某项在什么情况下不会被删除成功?

python - 如何在列表中运行我的标记器函数 - 模块对象不可调用?

c - BST构建树双指针

model - 如何使用 jena API 和 SPARQL 更新模型,例如。更新节点值

python - MongoDB 一共有三个字段

python - 无法删除 conda 包

python - 使用 Python 从服务器访问 Google Adsense API?

list - 何时选择容器/列表而不是 slice

MySQL 触发器问题

python - 循环并写入 CSV 文件?