2013-04-06 134 views
0

所有獨特的排列會是怎樣的這款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]) 
    } 
} 

謝謝

+0

[你嘗試過什麼?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Volatility 2013-04-06 08:57:10

+0

兩個while循環,EAC h用一個計數器作爲列表中的一個索引...但是我寧願在列表結構中使用X的本地值 – d1337 2013-04-06 09:04:16

回答

2

這裏有一些解決方案,不使用進口,並假設x已經被聲明爲含有10個元素的列表:

for i in range(10): # xrange in Python 2 
    for j in range(i, 10): 
     calc_something(x[i], x[j]) 

或使用enumerate功能:

for i, el in enumerate(x): 
    for j in x[i:]: 
     calc_something(el, j) 
0

最簡單的是:

for i in range(1,10): 
     for j in range(1,10): 
      calc_something(list[i],list[j]) 

代替硬編碼(1,10) 你可以說
爲我在列表中: 爲ji ñ列表:

+0

但是這會運行8,1和1,8的計算,這正是我想要避免的...'calc_something'是對稱的 – d1337 2013-04-06 09:14:23

+0

如果您想要唯一組合: i_vals = [] (i)範圍(1,10): i_vals.append(i) 對於範圍(1,10)中的j: if i not in i_vals: calc_something(list [i],list [j])' – 2013-04-06 09:25:56

0
x=[] 

for i in range(1,10): 
    for j in range(1,10): 
     calc_something(x[i],x[j]) 
4

這與itertools.combinations()做簡單:

import itertools 

... 

for i, j in itertools.combinations(x, 2): 
    calc_something(i, j) 

這給你想要的東西。具體來說,它將返回的元素順序如下:

[(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)] 
+0

+1如果沒有'itertools',我們會在哪裏? – Volatility 2013-04-06 09:29:59