社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

在python列表中只创建相同的对

Abdul Basit Niazi • 3 年前 • 1377 次点击  

如何在python列表中创建对。 列表=[1,2,3,4,5,6,7] 我想比较(1,2),(3,4)(5,6)

同对比较

我们怎样才能在所有的循环中

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132354
 
1377 次点击  
文章 [ 4 ]  |  最新文章 3 年前
The Amateur Coder Alik.Koldobs
Reply   •   1 楼
The Amateur Coder Alik.Koldobs    3 年前

如果我没听错的话,你可以选择列表并创建所有可能的配对。 要做到这一点,你应该使用itertools。

请看以下主题: 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)]

pppig
Reply   •   2 楼
pppig    3 年前

它将使用移动光标进行切片以获取值。

def func(l):
    prev_i, i = 0, 2
    while True:
        current = l[prev_i: i]
        if len(current) < 2:
            break
        yield current
        prev_i, i = i, i + 2


print(list(func([1,2,3,4,5,6,7])))

输出:

[[1, 2], [3, 4], [5, 6]]
XxJames07-
Reply   •   3 楼
XxJames07-    3 年前

你可以这样做:

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]]

mozway
Reply   •   4 楼
mozway    3 年前

你可以用 zip 并以不同的起点,每两项对输入列表进行切片:

lst = [1,2,3,4,5,6,7]

list(zip(lst[::2], lst[1::2]))

输出: [(1, 2), (3, 4), (5, 6)]