我将如何拆箱清单?

时间:2019-01-26 00:36:59

标签: python python-3.x

请理解,我已经搜索过它,并且它已经有一个answer。但是,我正在寻找另一种方式来获得此结果。尽管我认为可以使用duplicate (最有可能是groupby来解决这个问题,但这可能被标记为itertools

说我有一个列表data。而且我想一次假设3个值是假设列表是值的个数,以便排除末尾不正确的值。

data = [1, 2, 3, 4, 5, 6,...]

这是我要遍历列表的方式(此代码显然无法正常工作)

for a, b, c in data:
    #perform operations
    pass

现在使用上面的代码,我希望在每次迭代中分别将a, b, c依次为1, 2, 34, 5, 6。 我敢肯定,有一种比我链接的答案中更干净的方法。

对于那些不想单击链接以查看我所指的方法的懒惰人来说,这里是:

  

如果要通过成对的连续元素遍历列表,可以使用切片:

>>>myList = [4, 5, 7, 23, 45, 65, 3445, 234]
>>>for x,y in (myList[i:i+2] for i in range(0,len(myList),2)):
print(x,y)

4 5
7 23
45 65
3445 234

2 个答案:

答案 0 :(得分:7)

这是一个iterzip的hacky解决方案:

i =  [1, 2, 3, 4, 5, 6]
d = iter(i)

for a, b, c in zip(*[d]*3):
    print(a, b, c)

输出:

1 2 3
4 5 6

另外,如果您希望在原始列表不能被三整除的情况下迭代所有内容,则可以使用zip_longest中的itertools

from itertools import zip_longest


i =  [1, 2, 3, 4, 5, 6, 7]
d = iter(i)

for a, b, c in zip_longest(*[d]*3):
  print(a, b, c)

输出:

1 2 3
4 5 6
7 None None

答案 1 :(得分:1)

当您想要块中的下一个元素时,也许使用迭代器并增加迭代器:

data = [1, 2, 3, 4, 5, 6]
it = iter(data)

for x in it:
    a = x
    b = next(it)
    c = next(it)
    print(a, b, c)
    # Do something with a, b, and c
相关问题