社区所有版块导航
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中拆分列表

Marcus F • 3 年前 • 1215 次点击  

如何基于相邻元素拆分列表,如果我有一个

test = [3,5,7,1,10,17]

如果元素10和17相邻,我想拆分列表,以便拆分发生在 [3,5,7,1] [10,17] .

我知道有groupby,但我只知道如何使用它来检查是否存在一个元素,然后再拆分,而不是两个元素。

伪代码:

for i in list:
      if element[i] == 10 and element[i+1] == 17:
                  splitlist() # split before elements 10
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133294
 
1215 次点击  
文章 [ 3 ]  |  最新文章 3 年前
dsenese
Reply   •   1 楼
dsenese    3 年前

下面是一个简单的工作代码:

test = [3,5,7,1,10,17]

def neighbor_splitting():
    for x in test:
        if x == 10:
            index = test.index(x)
            list1 = test[:index]
            list2 = test[index:]
            return list1, list2

# [3, 5, 7, 1]
# [10, 17]

Ahmed
Reply   •   2 楼
Ahmed    3 年前

以下是一个基于您的输出的示例:

def split_list(test, match):
    idx = [test.index(i) for i in match]
    if sum([i - min(idx) for i in idx]) == sum(range(len(match))
        return [
            test[0:idx[0]],
            test[idx[0]:idx[-1]+1]
        ]

split_list(test=[3, 5, 7, 1, 10, 17], match=[10, 17])
Mark
Reply   •   3 楼
Mark    3 年前

你可以 zip() 列表本身带有偏移量以获得对。然后找到你正在寻找的一对的索引(假设这种情况发生一次,或者你只关心第一个)。然后把清单拼接起来:

test = [3,5,7,1,10,17]

def partition_on_pair(test, pair):
    index = next((i for i, n in enumerate(zip(test, test[1:])) if n == pair), len(test))
    return test[:index], test[index:]

partition_on_pair(test, (10, 17))
# ([3, 5, 7, 1], [10, 17])

partition_on_pair(test, (10, 19)) # doesn't exist, so you get an empty
#([3, 5, 7, 1, 10, 17], [])


partition_on_pair(test, (5, 7))
#([3], [5, 7, 1, 10, 17])

partition_on_pair(test, (3,5))
#([], [3, 5, 7, 1, 10, 17])