基于最大长度的列表提取列表

时间:2016-09-24 09:16:31

标签: python-2.7

我有两个列表列表,我需要使用更大的独占组来获取元素。例如,在下面的列表中,

L1 = [['A','B']]
L2 = [['A','B','C','D'],['A','B','E'],['B','E','F'],['A','G']]

L1, L2[0] & L2[1]不符合条件,因为它们都有'A'& 'B'。这留下了L2[2:3]。在此'B'是胜利者,因为它是较大群体的一部分。即set(L2[3])为3,但set(L2[2])为2。

因此,我的最终输出将为['B']

我编写了一个代码(对两个值工作正常),如下所示:

tmp = []; leng =[]
for i,j in L1: # (i,j allows for only two values)
    for k in L2:
        if i in k and j in k:
            pass
        else:
            tmp.append(k)
            leng.append(len(k))
print tmp;  print leng

for i, j in L1:
    for k in tmp:
        if i in k and len(k) > j in k and len(k) :
            print "Value in if", i
            break
        else:
            print "Value in else", j
            break

有人可以提出另一种pythonic方法吗? 我应该如何修改for i,j in L1:以容纳更多列表元素列表和每个元素的可变长度?

先谢谢。

AP

1 个答案:

答案 0 :(得分:1)

L1 = [['A','B'],['C','D','A']]
L2 = [['A','B','C','D'],['A','B','E'],['B','E','F'],['A','G'],['D','E','F','G']]
tmp = []; leng =[]
final_list=[]
for u in L1:
    for k in L2:
        if all(x in k for x in u):
            pass
        else:
            tmp.append(k)
            leng.append(len(k))
    ud = sorted([list(x) for x in set(tuple(x) for x in tmp)],key=len,reverse=True)
    print ud
    winner=[]
    for y in ud:
        for z in u: 
            for o in y:
                if o==z:
                    winner.append(o)
    final_list.append(winner[0])
print "Winners are: ",final_list

结果就像

 [['D', 'E', 'F', 'G'], ['B', 'E', 'F'], ['A', 'G']]
 winning order
 B
 A
 [['D', 'E', 'F', 'G'], ['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]
 winning order
 D
 A
 A

修改后的代码结果:

[['D', 'E', 'F', 'G'], ['B', 'E', 'F'], ['A', 'G']]
Winner in list ['A', 'B'] is : B
[['D', 'E', 'F', 'G'], ['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]
Winner in list ['C', 'D', 'A'] is : D

第二次修改结果:

Winners are: ['B', 'D']

注意:您可以修改输出以仅获得第一个结果。