返回信息流a = [1,2,3..]
有现成的函数从a里挑2个且有顺序,比如(1,2), (2,1), ....(1,3), (3,1)
这是一条镜像帖。来源:北邮人论坛 / python / #10092同步于 2015/11/27
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
列表里挑2个
tycoon0
2015/11/27镜像同步15 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
https://docs.python.org/3/library/itertools.html#itertools.permutations
这个怎么样?
十分感谢啊 有个疑惑,如果列表很大比如20000,这个效率高吗。
还有嘛更高效的方法不
【 在 nuanyangyang 的大作中提到: 】
: https://docs.python.org/3/library/itertools.html#itertools.permutations
: 这个怎么样?
【 在 tycoon0 的大作中提到: 】
: 十分感谢啊 有个疑惑,如果列表很大比如20000,这个效率高吗。
: 还有嘛更高效的方法不
真正的瓶颈是官方的Python的解释器(CPython),它比等效的C程序慢25倍左右。用CPython的话,手写两层循环并不比这个快。
如果用PyPy,那么itertools就是瓶颈了。看下面的测试。
如果性能是个问题,可以用C或者Java语言写。或者改用PyPy解释器。
perm.py:
from __future__ import print_function
from itertools import permutations
import sys
try:
size = int(sys.argv[1])
except IndexError:
size = 20000
def psum(n):
x = 0
for i,j in permutations(range(n), 2):
x = x + i + j
return x
print(psum(size))
perm_manual.py 这个例子手写两层循环。这里用的是for循环。而while循环反而慢。
from __future__ import print_function
from itertools import permutations
import sys
try:
size = int(sys.argv[1])
except IndexError:
size = 20000
def psum(n):
x = 0
for i in range(n):
for j in range(n):
if i != j:
x = x + i + j
return x
print(psum(size))
测量结果:
python3 perm.py 20000 46.50s user 0.01s system 100% cpu 46.507 total
python3 perm_manual.py 20000 62.26s user 0.01s system 99% cpu 1:02.27 total
pypy3 perm.py 20000 9.07s user 0.02s system 99% cpu 9.099 total
pypy perm_manual.py 20000 0.97s user 0.01s system 99% cpu 0.984 total
再来个C语言的:
#include <stdio.h>
long psum(long n) {
long x = 0;
for(long i = 0; i < n; i++) {
for(long j = 0; j < n; j++) {
x = x + i + j;
}
}
return x;
}
int main(int argc, char **argv) {
long size;
if (argc == 2) {
sscanf(argv[1], "%ld", &size);
} else {
size = 20000L;
}
long result = psum(size);
printf("%d\n", result);
return 0;
}
编译:
$ gcc --version
gcc (GCC) 5.2.0
...
$ gcc -O0 -o perm_manual_c_o0 perm_manual.c
$ gcc -O3 -o perm_manual_c_o3 perm_manual.c
运行:
./perm_manual_c_o0 20000 1.12s user 0.00s system 99% cpu 1.126 total
./perm_manual_c_o3 20000 0.59s user 0.00s system 99% cpu 0.588 total
PyPy仍然完爆未优化的C