列表的 Itertools 产品
Itertools product of list
我找到了这个功能,但我不想
A = [[1,2],[3,4]]
print list(product(*A))
[(1, 3), (1, 4), (2, 3), (2, 4)]
我只想在下面回答
[(1, 4),(2, 3)]
请问我该怎么做?
事实上,我不想在我的最终列表中的原始列表中的相同位置有一个数字。
我做到了:
def afficherListe(A):
n=len(A)
B=[]
for i in range (0,n,1):
for j in range (0,n,1):
if i!=j:
B.append(A[i][j])
return B
但它不起作用我只有 [2,3] 的答案...
我认为您可能想要从每列和每行中获取由 1 个项目组成的所有元组,就像在行列式计算中一样。如果是:
from itertools import permutations
def afficherListe(A):
"""A is a square matrix. Returns all tuples used in det(A)"""
n = len(A)
return [tuple(A[i][j] for i,j in enumerate(p)) for p in permutations(range(n))]
#tests:
A = [[1,2],[3,4]]
B = [[1,2,3],[4,5,6],[7,8,9]]
print(afficherListe(A))
print(afficherListe(B))
输出:
[(1, 4), (2, 3)]
[(1, 5, 9), (1, 6, 8), (2, 4, 9), (2, 6, 7), (3, 4, 8), (3, 5, 7)]
[(a,b) for a in A[0] for b in A[1] if A[0].index(a)!=A[1].index(b)]
输入:
A = [[1, 2], [3, 4]]
输出:
[(1, 4), (2, 3)]
我找到了这个功能,但我不想
A = [[1,2],[3,4]]
print list(product(*A))
[(1, 3), (1, 4), (2, 3), (2, 4)]
我只想在下面回答
[(1, 4),(2, 3)]
请问我该怎么做?
事实上,我不想在我的最终列表中的原始列表中的相同位置有一个数字。
我做到了:
def afficherListe(A):
n=len(A)
B=[]
for i in range (0,n,1):
for j in range (0,n,1):
if i!=j:
B.append(A[i][j])
return B
但它不起作用我只有 [2,3] 的答案...
我认为您可能想要从每列和每行中获取由 1 个项目组成的所有元组,就像在行列式计算中一样。如果是:
from itertools import permutations
def afficherListe(A):
"""A is a square matrix. Returns all tuples used in det(A)"""
n = len(A)
return [tuple(A[i][j] for i,j in enumerate(p)) for p in permutations(range(n))]
#tests:
A = [[1,2],[3,4]]
B = [[1,2,3],[4,5,6],[7,8,9]]
print(afficherListe(A))
print(afficherListe(B))
输出:
[(1, 4), (2, 3)]
[(1, 5, 9), (1, 6, 8), (2, 4, 9), (2, 6, 7), (3, 4, 8), (3, 5, 7)]
[(a,b) for a in A[0] for b in A[1] if A[0].index(a)!=A[1].index(b)]
输入:
A = [[1, 2], [3, 4]]
输出:
[(1, 4), (2, 3)]