首页 > 解决方案 > 如何配对列表的每两个元素?

问题描述

我有一个这样的清单

attach=['a','b','c','d','e','f','g','k']

我想将每两个相互跟随的元素配对:

lis2 = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'k')]

我做了以下事情:

Category=[] 
for i in range(len(attach)):
    if i+1< len(attach):
        Category.append(f'{attach[i]},{attach[i+1]}')

但后来我必须删除一半的行,因为它也会给出'b' ,'c'等等。我想也许有更好的方法

标签: pythonlist

解决方案


You can use zip() to achieve this as:

my_list = ['a','b','c','d','e','f','g','k']
new_list = list(zip(my_list[::2], my_list[1::2]))

where new_list will hold:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'k')]

This will work to get only the pairs, i.e. if number of the elements in the list are odd, you'll loose the last element which is not as part of any pair.

If you want to preserve the last odd element from list as single element tuple in the final list, then you can use itertools.zip_longest() (in Python 3.x, or itertools.izip_longest() in Python 2.x) with list comprehension as:

from itertools import zip_longest # In Python 3.x
# from itertools import izip_longest ## In Python 2.x

my_list = ['a','b','c','d','e','f','g','h', 'k']
new_list = [(i, j) if j is not None else (i,) for i, j in zip_longest(my_list[::2], my_list[1::2])]

where new_list will hold:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('k',)]
#   last odd number as single element in the tuple ^ 

推荐阅读