在给定成对排名的情况下,按适当顺序将项目放入列表中

时间:2016-12-12 00:29:59

标签: python

给出形式[(a,b),......]的项目对,其中(a,b)表示> b,例如:

[( '最好', '好'),( '最好', '好'),( '好', '好')] 我想输出一个表单列表:

[ '最好', '好', '好'] 由于某种原因,这很难。有什么想法吗?

4 个答案:

答案 0 :(得分:2)

展平它,删除重复项并排序:

>>> i = [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
>>> sorted({x for s in i for x in s})
[1, 2, 3, 4]

答案 1 :(得分:1)

虽然@ TigerhawkT3已经为您提供了解决方案,但这个可以适用于任意嵌套的列表/元组:

def flatten(seq):
  for el in seq:
    if isinstance(el, (tuple, list)):
      yield from flatten(el)
    else:
      yield el

l = [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
unique = sorted({el for el in flatten(l)})
print(unique) # [1, 2, 3, 4]

答案 2 :(得分:0)

def remove_duplicates(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

i = [(5,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
i = remove_duplicates(list(x for s in i for x in s))
print(i)  # prints [5, 2, 1, 3, 4]

j = [('excellent','good'),('excellent','great'),('great','good')]
j = remove_duplicates(list(x for s in j for x in s))
print(j)  # prints ['excellent', 'good', 'great']

参见参考:How do you remove duplicates from a list in whilst preserving order?

有关remove_duplicates()功能的说明,请参阅此stackoverflow post

答案 3 :(得分:0)

以下是否适合您的情况?

import itertools

lst = [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
final_list = sorted(set(itertools.chain(*lst)))
print(final_list)

至少在您提到的案例中似乎有效。