简体   繁体   English

遍历列表索引

[英]Iterate over a list indexes

I have a list of integers and I want to iterate over it changing some items in place: 我有一个整数列表,我想对其进行迭代以更改一些项目:

for i in xrange(len(items)):
    ...
    items[i] += step

I don't like this xrange(len(items)) . 我不喜欢这个xrange(len(items)) I could do for i, _ in enumerate(items) , but this is also not perfect. 我可以for i, _ in enumerate(items)for i, _ in enumerate(items) ,但这也不是完美的。

What do you do in such cases? 在这种情况下您会怎么做?

You can use list comprehension if this is a simple change: 如果这是一个简单的更改,则可以使用列表理解:

items = [x + step for x in items]

If you can't write it as a list comprehension, enumerate is the way to go: 如果您不能将其写为列表理解, enumerate方法:

for i, n in enumerate(items):
    ...
    items[i] = n + step

another way is to use numpy arrays. 另一种方法是使用numpy数组。 with them, it's as easy as: 与他们一样,就像:

array += step

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

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