Python就地列表分区

2024-06-25 23:29:26 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以使用标准python2.7(c++STL std::partition style)按谓词就地对列表进行分区?类似于itertools中的group_by,但没有附加数组?我需要递归地将数组分为两组,基于可变的条件,并且我受RAM数量的限制。在

我想要的是一个函数,比如:

partitionCPPStyle(data, startIndex, endIndex, condition)

这将导致data[startIndex:endIndex]list的所有元素在开始时都满足条件,并返回第一个不满足条件的元素的索引。没有拷贝,尽可能少地使用额外的内存。在

最后我编写了自己的实现:

def partitionInPlace(data, startIndex, endIndex, predicate):
    swapIndex = endIndex
    index = startIndex
    while(index < swapIndex):
        if not predicate(data[index]):
            temp = data[swapIndex]
            data[swapIndex] = data[index]
            data[index] = temp
            swapIndex = swapIndex-1
        else:
            index = index+1
    return index

有没有更有效的方法?在


Tags: 方法元素data标准indexstyle数组temp
1条回答
网友
1楼 · 发布于 2024-06-25 23:29:26

这是相对容易实现的-但既然你有“条件”(我将从这里开始使用术语“谓词”),就有一个复杂的问题:因为根本没有复制,结果结构可以“知道”某个项是否关注特定谓词的唯一方法是在访问时检查它-这意味着索引中会有“漏洞”。在

举一个更容易理解的例子:

a = list(range(20))
b = SlicedList(a, slice(10, 20), predicate=lambda x: x%2
len(b) # will correctly report (5)
b[0] # will raise ValueError as "10" fails the predicate
# so, 0-9 are valid indexes for "b", but only the contents 
# that attend the predicate will actually return a value
# you can safely iterate on b with a "for", though:
for item in b:
    print(item)  # (11, 13, 15, 17, 19)

不过,对于迭代来说,它应该可以很好地工作。在

^{pr2}$

另一个提示是尽快退出Python2.7—所有现代库和框架都可以在Python3上运行,而Python2现在正变得越来越过时。下面的代码对这两个都有效,但我必须为此做一个规定。在

相关问题 更多 >