[英]Calculate all unique permutations using nested loops in Python
What would be the python equivalent implementation for this C++ code: 此C ++代码的python等效实现是什么:
char x[10];
for (int i=0; i < 10; i++) {
for (int j=i; j < 10; j++) {
calc_something(x[i], x[j])
}
}
Thank you 谢谢
This is done simply with itertools.combinations()
: 只需使用
itertools.combinations()
:
import itertools
...
for i, j in itertools.combinations(x, 2):
calc_something(i, j)
This gives what you want. 这给出了您想要的。 Specifically, it will return the elements in this order:
具体来说,它将按以下顺序返回元素:
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9),
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9),
(2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9),
(3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9),
(4, 5), (4, 6), (4, 7), (4, 8), (4, 9),
(5, 6), (5, 7), (5, 8), (5, 9),
(6, 7), (6, 8), (6, 9),
(7, 8), (7, 9),
(8, 9)]
Here are some solutions that don't use imports, and assuming that x
is already declared as a list containing 10 elements: 以下是一些不使用导入的解决方案,并假设
x
已经声明为包含10个元素的列表:
for i in range(10): # xrange in Python 2
for j in range(i, 10):
calc_something(x[i], x[j])
Or using the enumerate
function: 或使用
enumerate
函数:
for i, el in enumerate(x):
for j in x[i:]:
calc_something(el, j)
simplest would be : 最简单的是:
for i in range(1,10):
for j in range(1,10):
calc_something( list[i],list[j])
instead of hard coding (1,10) you can say 而不是硬编码(1,10),您可以说
for i in list: for j in list: 对于列表中的i:对于列表中的j:
x=[]
for i in range(1,10):
for j in range(1,10):
calc_something(x[i],x[j])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.