9

所以我在另一篇文章中看到了下面的“坏”片段,但我看到的唯一选择涉及修补 Python。

for i in xrange(len(something)):
  workwith = something[i]
  # do things with workwith...

我该怎么做才能避免这种“反模式”?

4

5 回答 5

23

如果您需要知道循环体中的索引:

for index, workwith in enumerate(something):
    print "element", index, "is", workwith
于 2009-02-23T18:14:59.790 回答
22

Pythonic

for workwith in something:
    # do things with workwith
于 2009-02-23T18:12:36.207 回答
12

As there are two answers to question that are perfectly valid (with an assumption each) and author of the question didn't inform us about the destiny of index, the valid answer should read:

If you do not need index at all:

for workwith in something:
    print "element", workwith

If you need index:

for index, workwith in enumerate(something):
    print "element", index, "is", workwith

If my answer is not appropriate, comment please, and I'll delete it :)

于 2009-02-24T16:54:18.167 回答
0

例如:

[workwith(i) for i in something]
于 2009-02-23T18:13:05.113 回答
-3

是什么x?如果它是一个序列或迭代器或字符串,那么

for i in x:
    workwith = i

会正常工作。

于 2009-02-23T18:14:03.147 回答