[英]How to compare one element with other elements within the list
I have a list x = [a, b, c, d]
.我有一个列表
x = [a, b, c, d]
。
I want to compare:我想比较:
a
with b
, c
and d
.a
与b
, c
和d
。b
with a
, c
and d
.b
与a
, c
和d
。c
with a
, b
and d
.c
与a
, b
和d
。d
with a
, b
and c
.d
与a
, b
和c
。 This is the method I have used but it's not working as I want:这是我使用的方法,但它没有按我想要的那样工作:
for i in len(x):
for j in range(i+1, len(x)):
Compare(x[i], y[j])
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
"""
As a function:作为一个功能:
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')]
This looks like a good place to use itertools .这看起来是使用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
"""
If a == b
and b == a
then you can use combinations to get distinct pairs:如果
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
"""
A silly mistake, you forgot to print hte comparison.一个愚蠢的错误,你忘了打印 hte 比较。 Here is the solution:
这是解决方案:
For i in len(x):
For j in range(i+1, len(x)):
print(Compare(x[i], y[j]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.