简体   繁体   English

将位置编号添加到列表中的整数

[英]Adding the number of the position to an integer in a list

I need to add the number of the position of the integer in a list. 我需要添加列表中整数位置的数字。

list=[10,10,10,10]

then the outcome should be 那么结果应该是

[10,11,12,13]

I know it works whit a loop but I dont know how. 我知道它可以循环工作,但我不知道如何。 Thanks 谢谢

Get the index using enumerate and add each element to it's index using a list comprehension : 使用枚举获取索引,并使用列表 推导将每个元素添加到索引中:

lst = [10,10,10,10]
lst[:] = [i + ele for i,ele in enumerate(lst)]
print(lst)
[10, 11, 12, 13]

Which is the same as: 与以下内容相同:

lst = [10, 10, 10, 10]

for i, ele in enumerate(lst):
    lst[i]  = i + ele
print(lst)

i is the index of each element , ele is each actual element in the list. i是每个elementindexele是列表中的每个实际元素。 The lst[:] syntax means we modify the original list and using the list comp is a more efficient version of the regular loop. lst[:]语法意味着我们修改了原始列表,并且使用list comp是常规循环的更有效版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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