python - 如何配对列表的每两个元素?
问题描述
我有一个这样的清单
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'
等等。我想也许有更好的方法
解决方案
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 ^
推荐阅读
- java - 无法读取 jakarta.activation:jakarta.activation-api 的工件描述符
- python - Django 异步视图,AsyncIO
- list - Prolog 中最常见的子列表
- ruby-on-rails - 在rails中调用方法
- c++ - 如果 char *name = "Emma",为什么 &name 与 &name[0] 不同?
- flutter - Flutter streamProvider 未更新
- flutter - 颤振剪贴板选项未显示在 TextInputField 中
- sql - SQL中的时间戳差异
- php - 尝试发送电子邮件时调用字符串上的成员函数 getRealPath()
- python - 如何使用 pytesseract 对黄色立方体内的数字进行 detech