替代“for i in xrange(len(x))”

发布于 2024-07-14 05:31:46 字数 279 浏览 5 评论 0原文

所以我在另一篇文章中看到以下“坏”片段,但我见过的唯一替代方案涉及修补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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不打扰别人 2024-07-21 05:31:46

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

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

If you need to know the index in the loop body:

for index, workwith in enumerate(something):
    print "element", index, "is", workwith
嘿看小鸭子会跑 2024-07-21 05:31:46

请参阅Pythonic

for workwith in something:
    # do things with workwith

See Pythonic

for workwith in something:
    # do things with workwith
鸠书 2024-07-21 05:31:46

因为有 两个 问题的答案完全有效(每个假设都有一个假设)并且问题的作者没有'如果没有告诉我们索引的命运,有效的答案应该是:

如果您根本不需要索引

用于处理某事: 
      打印“元素”,使用 
  

如果您需要索引

对于索引,在枚举(某事)中使用: 
      打印“元素”,索引,“是”,工作 
  

如果我的答案不合适,请评论,我会删除它:)

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 :)

入怼 2024-07-21 05:31:46

例如:

[workwith(i) for i in something]

for example:

[workwith(i) for i in something]
预谋 2024-07-21 05:31:46

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

for i in x:
    workwith = i

就可以正常工作。

What is x? If its a sequence or iterator or string then

for i in x:
    workwith = i

will work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文