小编典典

Python-遍历列表中的每两个元素

python

如何进行for循环或列表理解,以便每次迭代都给我两个元素?

l = [1,2,3,4,5,6]

for i,k in ???:
    print str(i), '+', str(k), '=', str(i+k)

输出:

1+2=3
3+4=7
5+6=11

阅读 3474

收藏
2020-02-10

共2个答案

小编典典

你需要一个pairwise()(或grouped())实施。

对于Python 2:

from itertools import izip

def pairwise(iterable):
    "s -> (s0, s1), (s2, s3), (s4, s5), ..."
    a = iter(iterable)
    return izip(a, a)

for x, y in pairwise(l):
   print "%d + %d = %d" % (x, y, x + y)

或更笼统地说:

from itertools import izip

def grouped(iterable, n):
    "s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
    return izip(*[iter(iterable)]*n)

for x, y in grouped(l, 2):
   print "%d + %d = %d" % (x, y, x + y)

在Python 3中,你可以替换izip为内置zip()函数,然后删除import。

所有信贷蒂诺对他的回答到我的问题,我发现这是非常有效的,因为它只是在列表上循环一次,并在此过程中不会产生任何不必要的名单。

注意:不要将其与Python自己的文档中的pairwise配方混淆,后者由@lazyr在评论中指出。itertoolss -> (s0, s1), (s1, s2), (s2, s3), ...

对于想要在Python 3上使用mypy进行类型检查的用户而言,几乎没有什么附加的:

from typing import Iterable, Tuple, TypeVar

T = TypeVar("T")

def grouped(iterable: Iterable[T], n=2) -> Iterable[Tuple[T, ...]]:
    """s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), ..."""
    return zip(*[iter(iterable)] * n)
2020-02-10
小编典典

您可以使用LocalDate在Java中完成此操作:

LocalDate dt = LocalDate.parse("2019-09-20"); 
System.out.println(dt);   
DateTimeFormatter ft = DateTimeFormatter.ofPattern("dd MMM", new Locale("sv","SE")); 
System.out.println(ft.format(dt));
2020-12-03