我有一个列表x = [a, b, c, d]
。
我要比较:
a
包含b
,c
和d
。b
和a
,c
和d
。c
与a
,b
和d
。 d
,a
和b
的第四元素c
。这是我使用过的方法,但无法正常运行:
for i in len(x):
for j in range(i+1, len(x)):
Compare(x[i], y[j])
答案 0 :(得分:0)
for i in range(len(x)):
for el in x[:i] + x[(i+1):]:
print("Compare {} with {}".format(x[i], el))
# or: Compare(x[i], el)
"""
Output:
Compare a with b
Compare a with c
Compare a with d
Compare b with a
Compare b with c
Compare b with d
Compare c with a
Compare c with b
Compare c with d
Compare d with a
Compare d with b
Compare d with c
"""
功能:
def exclusive_compare(l, comparefun):
return [comparefun(l[i], el) for el in l[:i] + l[(i+1):] for i in range(len(l))]
exclusive_compare(l, lambda x, y: (x, y))
Out[9]:
[('a', 'b'),
('a', 'c'),
('a', 'd'),
('b', 'a'),
('b', 'c'),
('b', 'd'),
('c', 'a'),
('c', 'b'),
('c', 'd'),
('d', 'a'),
('d', 'b'),
('d', 'c')]
答案 1 :(得分:0)
这似乎是使用itertools的好地方。
for i in list(itertools.permutations(x, 2)):
print("Compare {0} with {1}".format(*i))
"""
Compare a with b
Compare a with c
Compare a with d
Compare b with a
Compare b with c
Compare b with d
Compare c with a
Compare c with b
Compare c with d
Compare d with a
Compare d with b
Compare d with c
"""
如果a == b
和b == a
,则可以使用组合来获得不同的对:
for i in list(itertools.combinations(x, 2)):
print("Compare {0} with {1}".format(*i))
"""
Compare a with b
Compare a with c
Compare a with d
Compare b with c
Compare b with d
Compare c with d
"""
答案 2 :(得分:-1)
一个愚蠢的错误,您忘记打印比较了。解决方法如下:
For i in len(x):
For j in range(i+1, len(x)):
print(Compare(x[i], y[j]))