gpt4 book ai didi

python - 两个列表之间更快的元素滚动置换交换

转载 作者:行者123 更新时间:2023-12-03 23:04:06 25 4
gpt4 key购买 nike

我有两个列表,X 和 Y。X = [1,2,3]Y = ['A','B','C']我想从列表 A 中获取两个的所有组合,并将其放在第二个列表中的任何位置。
从最初的第二个列表中,我想将所有元素一个一个地放在列表 X 中的任何位置。
结果应该是这样的:

# Original lists: (X = [1,2,3], Y = ['A','B','C'])

[
([1, 'A'], ['B', 'C', 2, 3]), # 2,3 went to list (Y) and 'A' went to list (X)
([1, 'B'], ['A', 'C', 2, 3]), # 2,3 went to list (Y) and 'B' went to list (X)
([1, 'C'], ['A', 'B', 2, 3]), # 2,3 went to list (Y) and 'C' went to list (X)
([2, 'A'], ['B', 'C', 1, 3]), # 1,3 went to list (Y) and 'A' went to list (X)
([2, 'B'], ['A', 'C', 1, 3]), # 1,3 went to list (Y) and 'B' went to list (X)
([2, 'C'], ['A', 'B', 1, 3]), # 1,3 went to list (Y) and 'C' went to list (X)
([3, 'A'], ['B', 'C', 1, 2]), # 1,2 went to list (Y) and 'A' went to list (X)
([3, 'B'], ['A', 'C', 1, 2]), # 1,2 went to list (Y) and 'B' went to list (X)
([3, 'C'], ['A', 'B', 1, 2]) # 1,2 went to list (Y) and 'C' went to list (X)
]
我的实现是这样的:
def itwo(l1,l2):
ln2 = l2[:]
final = []
z = list(it.combinations(l1, 2))
for i in range(len(z)):
ln1 = [ elem for elem in l1 if elem not in list(z[i])]
ln2 = l2 + list(z[i])
for y in range(len(l2)):
ln1.append(l2[y])
ln2.remove(l2[y])
final.append((ln1, ln2))
ln2 = l2 + list(z[i])
ln1 = [ elem for elem in l1 if elem not in list(z[i])]
return(final)
X有 100 个元素和 Y十个,例如 A = [1, 2, ...., 100]B = [A, B, C, D, E, F, G, H, I, J]在我的 PC 中的性能是:
   Ordered by: internal time

ncalls tottime percall cumtime percall filename:lineno(function)
49500 0.910 0.000 0.910 0.000 C:\...\test.py:25(<listcomp>)
4950 0.086 0.000 0.086 0.000 C:\...\test.py:18(<listcomp>)
1 0.040 0.040 1.049 1.049 C:\...\test.py:13(itwo)
99000 0.006 0.000 0.006 0.000 {method 'append' of 'list' objects}
49500 0.006 0.000 0.006 0.000 {method 'remove' of 'list' objects}
4951 0.000 0.000 0.000 0.000 {built-in method builtins.len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}


207903 function calls in 1.049 seconds
我想知道使用另一种方法是否可以更快。

最佳答案

似乎您应该可以使用 itertools.product 来做到这一点。并设置函数以删除嵌套循环:

import itertools as it

X = range(100)
Y = ['A','B','C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

def itwo_s(l1,l2):
s1 = set(l1)
s2 = set(l2)

for l in it.product(l1, l2):
yield [list(l), [*s2.difference(l), *s1.difference(l)]]


list(itwo_s(X, Y))
定时:
# original:
%timeit itwo(X, Y)
# 1.55 s ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# code above:
%timeit list(itwo_s(X, Y))
# 2.97 ms ± 179 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
因为您依赖于集合,所以您对子列表进行松散排序以换取速度。不确定这是否重要。

关于python - 两个列表之间更快的元素滚动置换交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63783047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com