python单行将dict列表和list列表相关联

时间:2019-01-22 14:56:15

标签: python list dictionary

给出一个项目列表(音乐家)和一个词典列表(仪器),如何以 pythonic方式使它们之间建立关联?

因此,要简化我的实际情况,请考虑以下几点:

musicians  = [[700,"James","Hetfield", "jh@metallica.com","N/A"],
              [701,"Lars","Ulrich","lu@metallica.com","N/A"],
              [702,"Kirk","Hammett","kh@metallica.com","N/A"],
              [703,"Robert","Trujillo", "rt@metallica.com","N/A"]]

instruments= ({700:"guitar"},{701:"drums"})

我的目标是将乐器中的N / A替换为音乐家。

下面的代码可以解决问题(但直觉来自java / c ++)

for m in musicians:
    for i in instruments:
        if m[0] in i:
            m[4]=i[m[0]]

正确的预期结果将是:

[[700, 'James', 'Hetfield', 'jh@metallica.com', 'guitar'], [701, 'Lars', 'Ulrich', 'lu@metallica.com', 'drums'], [702, 'Kirk', 'Hammett', 'kh@metallica.com', 'N/A'], [703, 'Robert', 'Trujillo', 'rt@metallica.com', 'N/A']]

问:是否有经典的方法可以在python中完成?

2 个答案:

答案 0 :(得分:5)

您可以使用collections.ChainMap来组合您的乐器映射,然后使用列表推导:

from collections import ChainMap

cm = ChainMap(*instruments)
musicians = [[*x[:-1], cm.get(x[0], x[-1])] for x in musicians]

print(musicians)

# [[700, 'James', 'Hetfield', 'jh@metallica.com', 'guitar'],
#  [701, 'Lars', 'Ulrich', 'lu@metallica.com', 'drums'],
#  [702, 'Kirk', 'Hammett', 'kh@metallica.com', 'N/A'],
#  [703, 'Robert', 'Trujillo', 'rt@metallica.com', 'N/A']]

答案 1 :(得分:3)

如果字典列表中没有重复的键,则将其合并

musicians = [[700, "James", "Hetfield", "jh@metallica.com", "N/A"],
             [701, "Lars", "Ulrich", "lu@metallica.com", "N/A"],
             [702, "Kirk", "Hammett", "kh@metallica.com", "N/A"],
             [703, "Robert", "Trujillo", "rt@metallica.com", "N/A"]]

instrumets = ({700: "guitar"}, {701: "drums"})

instruments_dict = {}
for d in instrumets:
    instruments_dict.update(d)
for m in musicians:
    m[-1] = instruments_dict.get(m[0], m[-1]) # thanks to  Ev. Kounis