替代“for i in xrange(len(x))”
所以我在另一篇文章中看到以下“坏”片段,但我见过的唯一替代方案涉及修补Python。
for i in xrange(len(something)):
workwith = something[i]
# do things with workwith...
我该怎么做才能避免这种“反模式”?
So I see in another post the following "bad" snippet, but the only alternatives I have seen involve patching Python.
for i in xrange(len(something)):
workwith = something[i]
# do things with workwith...
What do I do to avoid this "antipattern"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您需要知道循环体中的索引:
If you need to know the index in the loop body:
请参阅Pythonic
See Pythonic
因为有 两个 问题的答案完全有效(每个假设都有一个假设)并且问题的作者没有'如果没有告诉我们索引的命运,有效的答案应该是:
如果我的答案不合适,请评论,我会删除它:)
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 my answer is not appropriate, comment please, and I'll delete it :)
例如:
for example:
什么是
x
? 如果它是序列、迭代器或字符串,那么就可以正常工作。
What is
x
? If its a sequence or iterator or string thenwill work fine.