如何将一个元素与列表中的其他元素进行比较

时间:2020-01-20 23:37:28

标签: python list

我有一个列表x = [a, b, c, d]

我要比较:

  1. 第一个元素a包含bcd
  2. 第二个元素bacd
  3. 第三元素cabd
  4. 带有dab的第四元素c

这是我使用过的方法,但无法正常运行:

for i in len(x):
    for j in range(i+1, len(x)):
        Compare(x[i], y[j])

3 个答案:

答案 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 == bb == 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]))