获得成对的:一个项目和其他项目,通过一个python列表

2024-04-26 05:31:46 发布

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

我想这么做

from some_cool_library import fancy_calculation

arr = [1,2,3,4,5]
for i, item in enumerate(arr):
    the_rest = arr[:i] + arr[i+1:]
    print(item, fancy_calculation(the_rest))


[Expected output:] # some fancy output from the fancy_calculation
12.13452134
2416245.4315432
542.343152
15150.1152
10.1591

但我想知道是否有一种更具python风格的方法或现有的库来获得上面所示的对。你知道吗

当前实现的问题是,the_rest变量需要大约O(n)个内存。有没有办法不需要额外的内存分配就可以做到这一点?你知道吗

for item, the_rest in some_cool_function(arr):
    print(item, fancy_calculation(the_rest))

Tags: the内存infromrestforoutputlibrary
2条回答

在“pythonicity”和可读性方面,我认为你的代码是很好的。你知道吗

如果您关心循环中的列表分配,可以这样优化:

arr = [1,2,3,4,5]

the_rest = arr[1:]
for i, item in enumerate(arr):
    print(item, fancy_calculation(the_rest))

    if i < len(arr) - 1:
        the_rest[i] = arr[i]

但是请记住:fancy_calculation将在每次迭代中获得相同的列表引用,因此:(a)不要修改它,(b)不要延迟计算(例如,单独的使用者线程),因为内容将在下一次迭代中更改。你知道吗

如果您只需要其余的元素(从您的编辑中可以看出),那么可以使用^{}来获得具有一定数量元素的所有组合,如下所示:

from itertools import combinations

arr = [1, 2, 3, 4, 5]

for combination in combinations(arr, len(arr)-1):
    print(sum(combination))

注意:顺序与您提供的相反,如果顺序重要,您可以在使用arr[::-1]之前反转arr

相关问题 更多 >