所以我在另一篇文章中看到了下面的“坏”片段,但我看到的唯一选择涉及修补 Python。
for i in xrange(len(something)):
workwith = something[i]
# do things with workwith...
我该怎么做才能避免这种“反模式”?
所以我在另一篇文章中看到了下面的“坏”片段,但我看到的唯一选择涉及修补 Python。
for i in xrange(len(something)):
workwith = something[i]
# do things with workwith...
我该怎么做才能避免这种“反模式”?
如果您需要知道循环体中的索引:
for index, workwith in enumerate(something):
print "element", index, "is", workwith
for workwith in something:
# do things with workwith
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 :)
例如:
[workwith(i) for i in something]
是什么x
?如果它是一个序列或迭代器或字符串,那么
for i in x:
workwith = i
会正常工作。