如何按两两循环遍历列表?

发布于 2024-09-04 12:49:49 字数 195 浏览 6 评论 0原文

我想循环遍历一个 Python 列表并一次处理 2 个列表项。用另一种语言来说是这样的:

for(int i = 0; i < list.length(); i+=2)
{
   // do something with list[i] and list[i + 1]
}

完成此任务的最佳方法是什么?

I want to loop through a Python list and process 2 list items at a time. Something like this in another language:

for(int i = 0; i < list.length(); i+=2)
{
   // do something with list[i] and list[i + 1]
}

What's the best way to accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(7

北方。的韩爷 2024-09-11 12:49:49

您可以使用步长为 2 的范围

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

注意:使用Python 2 中的 xrange 而不是 range,因为它更有效,因为它生成可迭代对象,而不是整个列表。

You can use a range with a step size of 2:

Python 2

for i in xrange(0,10,2):
  print(i)

Python 3

for i in range(0,10,2):
  print(i)

Note: Use xrange in Python 2 instead of range because it is more efficient as it generates an iterable object, and not the whole list.

本王不退位尔等都是臣 2024-09-11 12:49:49

您还可以使用此语法 (L[start:stop:step]):

mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
    print i,
# prints 1 3 5 7 9

for i in mylist[1::2]:
    print i,
# prints 2 4 6 8 10

其中第一个数字是起始索引(默认为列表开头或 0),第二个数字是结束切片索引(默认为列表末尾),第三位数字是偏移量或步长。

You can also use this syntax (L[start:stop:step]):

mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
    print i,
# prints 1 3 5 7 9

for i in mylist[1::2]:
    print i,
# prints 2 4 6 8 10

Where the first digit is the starting index (defaults to beginning of list or 0), 2nd is ending slice index (defaults to end of list), and the third digit is the offset or step.

油焖大侠 2024-09-11 12:49:49

我认为最简单的就是:

it = iter([1,2,3,4,5,6])
for x, y in zip(it, it):
    print x, y

Out: 1 2
     3 4
     5 6

没有额外的进口或任何东西。在我看来,非常优雅。

The simplest in my opinion is just this:

it = iter([1,2,3,4,5,6])
for x, y in zip(it, it):
    print x, y

Out: 1 2
     3 4
     5 6

No extra imports or anything. And very elegant, in my opinion.

宛菡 2024-09-11 12:49:49

如果您使用的是 Python 2.6 或更高版本,您可以使用来自itertools 模块:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

调用如下this:

for item1, item2 in grouper(2, l):
    # Do something with item1 and item2

请注意,在 Python 3.x 中,您应该使用 zip_longest 而不是 izip_longest

If you're using Python 2.6 or newer you can use the grouper recipe from the itertools module:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Call like this:

for item1, item2 in grouper(2, l):
    # Do something with item1 and item2

Note that in Python 3.x you should use zip_longest instead of izip_longest.

攒眉千度 2024-09-11 12:49:49
nums = range(10)
for i in range(0, len(nums)-1, 2):
    print nums[i]

有点脏,但它有效。

nums = range(10)
for i in range(0, len(nums)-1, 2):
    print nums[i]

Kinda dirty but it works.

半仙 2024-09-11 12:49:49

这可能不如 izip_longest 解决方案那么快(我实际上没有测试它),但它可以与 python < 一起使用。 2.6(izip_longest是在2.6中添加的):

from itertools import imap

def grouper(n, iterable):
    "grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
    args = [iter(iterable)] * n

    return imap(None, *args)

如果您需要早于2.3,您可以用内置地图替换imap。缺点是不提供自定义填充值的能力。

This might not be as fast as the izip_longest solution (I didn't actually test it), but it will work with python < 2.6 (izip_longest was added in 2.6):

from itertools import imap

def grouper(n, iterable):
    "grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
    args = [iter(iterable)] * n

    return imap(None, *args)

If you need to go earlier than 2.3, you can substitute the built-in map for imap. The disadvantage is that it provides no ability to customize the fill value.

她比我温柔 2024-09-11 12:49:49

如果您可以控制列表的结构,那么最Pythonic的事情可能是将其从: 更改

l=[1,2,3,4]

为:

l=[(1,2),(3,4)]

然后,您的循环将是:

for i,j in l:
    print i, j

If you have control over the structure of the list, the most pythonic thing to do would probably be to change it from:

l=[1,2,3,4]

to:

l=[(1,2),(3,4)]

Then, your loop would be:

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