在二维列表中搜索一维列表的元素

时间:2019-05-06 10:23:24

标签: python list search

我有两个列表,一个列表的形式:

A = ["qww","ewq","ert","ask"]
B = [("qww",2) ,("ert",4) , ("qww",6), ("ewq" , 5),("ewq" , 10),("ewq" , 15),("ask",11)]

我必须进行处理,以使最终输出为

C = A = [("qww",8),("ewq",20),("ert",4),("ask",11)]

为此,我编写了代码:

# in code temp_list is of form A
# in code total_list is of form B
# in code final is of form C

def ispresent(key,list):
    for qwerty in list:
        if qwerty == key:
            return 1
        else:
            return 0

def indexreturn(key,list):
    counter = 0
    for qwerty in list:
        if qwerty != key:
            counter = counter + 1
        else:
            return counter

def mult_indexreturn(key,list):
    for i in range(len(list)):
        if key == list[i][0]:
                return i

final = map(lambda n1, n2: (n1,n2 ), temp_list,[ 0 for _  in range(len(temp_list))])

for object2 in total_list:#****
    for object1 in temp_list:
        if object2 == object1:
            final[  indexreturn(object2,final) ][1] = final[  indexreturn(object2, final)  ][1] + object2[mult_indexreturn(object2,total_list)][1]#total_list[ mult_indexreturn(object2,total_list) ][1]
print(final)

它应该将输出作为C类型列表提供,但不提供任何内容 但是C = [(“ qww”,0),(“ ewq”,0),(“ ert”,0),(“ ask”,0)]

根据我的主要问题在我的循环部分中(带有****注释),是否存在逻辑问题或其他的东西。 我提供了很多代码,以便您可以了解我的代码的工作原理

3 个答案:

答案 0 :(得分:1)

您可以使用方法fromkeys()来构建字典,随后可以使用for循环来累积整数:

A = ["qww","ewq","ert","ask"]
B = [("qww",2) ,("ert",4) , ("qww",6), ("ewq" , 5),("ewq" , 10),("ewq" , 15),("ask",11)]

C = dict.fromkeys(A, 0)
# {'qww': 0, 'ewq': 0, 'ert': 0, 'ask': 0}

for k, v in B:
    C[k] += v

C = list(C.items())
# [('qww', 8), ('ewq', 30), ('ert', 4), ('ask', 11)]

答案 1 :(得分:0)

尝试一下:

from collections import defaultdict 

result = defaultdict(int) 
for i in A: 
    result[i] = sum([j[1] for j in B if j[0] == i])

然后tuple(result.items())将成为您的输出。

或者您也可以只一行完成它:

result = tuple({i:sum([j[1] for j in B if j[0] == i]) for i in A}.items())

答案 2 :(得分:0)

使用collection.defaultdict

例如:

from collections import defaultdict 
A = ["qww","ewq","ert","ask"]
B = [("qww",2) ,("ert",4) , ("qww",6), ("ewq" , 5),("ewq" , 10),("ewq" , 15),("ask",11)]


result = defaultdict(int) 
for key, value in B: 
    if key in A:             #Check if Key in A. 
        result[key] += value  #Add Value. 
print(result)

输出:

defaultdict(<type 'int'>, {'qww': 8, 'ert': 4, 'ewq': 30, 'ask': 11})