簡體   English   中英

根據python中的條件索引添加子列表元素

[英]Adding sublists elements based on indexing by condition in python

我有如下列表

a=[['a',1,2,1,3],['b',1,3,4,3],['c',1,3,4,3]]
b=[['b',1,3,4,3],['c',1,3,4,3]]

如果第一個子列表元素與其他列表子列表元素匹配,我想基於索引添加元素

試過以下:

from operator import add 

res_list1=[]
    for a1 in a:
        for b1 in b:
            if a1[0]==b1[0]:
                res_list = [map(add, a1[1:], b1[1:])]
                res = [[a1[0],i,j,k,l] for i,j,k,l in res_list]
                res_list1.append(res[0])
            else:
                res_list=a1
                res_list1.append(res_list)

    print res_list1

但輸出結果如下:

res_list1=[['a', 1, 2, 1, 3], ['a', 1, 2, 1, 3], ['b', 2, 6, 8, 6], ['b', 1, 3, 4, 3], ['c', 1, 3, 4, 3], ['c', 2, 6, 8, 6]]

但正確的輸出應該是:

res_list1=[['a', 1, 2, 1, 3], ['b', 2, 6, 8, 6], ['c', 2, 6, 8, 6]]

這是一個基於itertools的方法:

from operator import itemgetter
from itertools import groupby, islice

l = sorted(a+b)
[[k] + [sum(i) for i in islice(zip(*v),1,None)] for k,v in groupby(l, key=itemgetter(0))]
# [['a', 1, 2, 1, 3], ['b', 2, 6, 8, 6], ['c', 2, 6, 8, 6]]

你可以定義一個像這樣的函數:

def add_elements(a, b):
    b_dict = {i[0]: i[1:] for i in b}
    default = [0 for _ in a][:-1]
    return [i[:1] + [sum(x) for x in zip(i[1:], b_dict.get(i[0], default))] for i in a]

並使用您的列表作為參數調用它:

add_elements(a, b)
#[['a', 1, 2, 1, 3], ['b', 2, 6, 8, 6], ['c', 2, 6, 8, 6]]

請參閱@ zipa的答案,使用詞典獲得更多Pythonic(高效,簡短,可讀,整體更好)的解決方案。

我將嘗試使用您自己的代碼的原始結構來回答:

from operator import add

a=[['a',1,2,1,3],['b',1,3,4,3],['c',1,3,4,3]]
b=[['b',1,3,4,3],['c',1,3,4,3]]

res_list1=[]
for a1 in a:
    found_match = False
    for b1 in b:
        if a1[0]==b1[0]:
            found_match = True
            res_list = [map(add, a1[1:], b1[1:])]
            res = [[a1[0],i,j,k,l] for i,j,k,l in res_list]
            res_list1.append(res[0])
    if not found_match:
        res_list = a1
        res_list1.append(res_list)

print(res_list1)

你遇到的問題總是附加到res_list1 ,內循環的每次迭代(因此對於每個(a1,b1)對)。 我解決這個問題的方法是“記住”(即 - 保留在一個布爾變量中)我們是否在b找到了a1的匹配,並且只有在沒有的情況下 - 將原始列表添加到結果中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM