![](/img/trans.png)
[英]Loop through list and compare against nested dict. avoiding KeyError - Python
[英]Nested loop through list avoiding same element
我根本無法很好地解釋這個概念,但我正在嘗試使用嵌套循環遍歷列表,但我不知道如何使用相同的元素來避免它們。
list = [1, 2, 2, 4]
for i in list:
for j in list:
print(i, j) # But only if they are not the same element
所以輸出應該是:
1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
編輯,因為解決方案不適用於所有場景:
if i != j
解決方案僅在列表中的所有元素都不同時才有效,我顯然選擇了一個糟糕的例子,但我的意思是相同的元素而不是相同的數字; 我改變了例子
您可以比較兩次迭代的索引:
lst = [1, 2, 2, 4]
for i, a in enumerate(lst):
for j, b in enumerate(lst):
if i != j:
print(a, b)
您還可以考慮使用itertools.permutations
來滿足您的目的:
lst = [1, 2, 2, 4]
from itertools import permutations
for i, j in permutations(lst, 2):
print(i, j)
兩者都會輸出:
1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
簡單地:
if i != j:
print(i, j)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.