如何在python列表中创建对。列表= 1,2,3,4,5,6,7我想比较(1,2),(3,4) (5,6)
同对比较
我们如何循环通过所有的对
发布于 2022-01-16 11:27:24
您可以使用zip并将输入列表分割为具有不同起点的每两项:
lst = [1,2,3,4,5,6,7]
list(zip(lst[::2], lst[1::2]))输出:[(1, 2), (3, 4), (5, 6)]
发布于 2022-01-16 11:21:36
如果我正确地理解了你,你想要拿出这个列表,并创建所有可能的配对。要做到这一点,您应该使用迭代工具。
看看以下主题:How to split a list into pairs in all possible ways。
import itertools
list(itertools.combinations(range(6), 2))
#[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]发布于 2022-01-16 11:39:38
你可以这样做:
list = [1,2,3,4,5,6,7]
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):yield lst[i:i + n]
sublist = [x for x in chunks(list, 2)]
for x in sublist:
if x.__len__() > 1:continue
else:sublist.remove(x)
print(sublist)输出:
[[1,2],[3,4],[5,6]]
https://stackoverflow.com/questions/70729538
复制相似问题