有列表名爲L. 其中包含其他列表:L = [A,B,C,... N] 我想循環,其中B不等於A(請參閱#2) 喜歡的東西:對B不是在L:Python3中的雙循環
for A in L: #1
for B in L: #2
我怎樣才能做到這一點?
有列表名爲L. 其中包含其他列表:L = [A,B,C,... N] 我想循環,其中B不等於A(請參閱#2) 喜歡的東西:對B不是在L:Python3中的雙循環
for A in L: #1
for B in L: #2
我怎樣才能做到這一點?
通過指數剛剛訪問列表的其餘部分:
for i in xrange(len(L)-1):
for j in xrange(i+1, len(L)):
#L[i] != L[j] always, and will check just one list against the others once
更好的解決方案使用itertools
,無論是with permutations
或with combinations
:
import itertools
# If it's okay to see L[1], L[2], and later L[2], L[1], that is, order sensitive,
# matching your original question's specification of only avoiding pairing with self:
for A, B in itertools.permutations(L, 2):
...
# If you only want to see L[x] paired with L[y] where y > x,
# equivalent to results of Daniel Sanchez's answer:
for A, B in itertools.combinations(L, 2):
...
無論是其中之一是顯著比使用嵌套循環速度越快需要索引(和獎金,只需要一級縮進,減少代碼中的「箭頭模式」)。
如果環路的身體print(A, B, sep=',', end=' ')
和L = [1, 2, 3]
的permutations
迴路的輸出將是:
1,2 1,3 2,1 2,3 3,1 3,2
爲combinations
,你可以獲得:
1,2 1,3 2,3
所以選擇匹配爲準你想要的行爲。
使用itertools
功能的另一個好處是,他們會工作得很好,當L
是一個非序列集合(如set
),或者當它是一次只能經過一個迭代器(他們會緩存這些值在內部,因此它們可以多次產生它們)。其他解決方案需要明確轉換爲list
/tuple
等來處理「L
是一次性迭代器」的情況。
您可以使用if
語句來過濾掉不想要的情況:
for A in L:
for B in L:
if A == B:
continue # skip
# do stuff ...
這需要執行len(L)** 2'次的顯式比較。並假設你的'list'包含同類(或至少可比)類型。並且應該拒絕相等的(但不是等同的)配對(這是不明確的),這意味着奇怪的東西'L = [1,True]'根本不會產生任何輸出,而'L = [float('nan' )]'會產生一個與它自身配對的輸出。如果可以用其他方式完成(例如'itertools'方法,或者失敗,索引比較,避免了相等問題,以及由緩存引起的邊緣情況),最好避免這種「每循環測試」。 – ShadowRanger
'xrange'不會在Python 3,使用'range'存在。 – Rufflewind
這將防止'L [1]'與L [0]配對(按此順序)。 OP _seems_想要將'L [0],L [1]'作爲一對並且'L [1],L [0]'作爲一對,因爲原始循環將產生兩者,並且他們只想省略'L [x],L [x]'配對... – ShadowRanger