处理驻留在列表中的元组列表中的数据

process data in a list of tuples that resides in a list

我在列表中有一个元组列表,如下所示,sof = [[], [('ABC', '0703', '', '', '', '', '', ''), ('ABC', '0702', '', '', '', '', '', '')], [('CDF', '0702', '', '', '', '', '', ''), ('CDF', '0702', '', '', '', '', '', '')] , [('', '', '', '', '', '', 'XYZ', '0702')]]

我想处理该列表中的数据以将其保存在字典中,同时跳过冗余重复数据作为 dic = { 'ABC' :0703 , 'CDF': 0702 , 'XYZ' : 0702 },

到目前为止,我正在使用 3 个内部循环来遍历这些元组中的值,如下所示,

for i in sof: for j in i: for k in j: print(k)

尝试:

sof = [
    [],
    [
        ("ABC", "0703", "", "", "", "", "", ""),
        ("ABC", "0702", "", "", "", "", "", ""),
    ],
    [
        ("CDF", "0702", "", "", "", "", "", ""),
        ("CDF", "0702", "", "", "", "", "", ""),
    ],
    [("", "", "", "", "", "", "XYZ", "0702")],
]

out = {}
for subl in sof:
    for tpl in subl:
        tpl = [t for t in tpl if t != ""]
        if len(tpl) == 2:
            out[tpl[0]] = tpl[1]

print(out)

打印:

{'ABC': '0702', 'CDF': '0702', 'XYZ': '0702'}

调整 Andrej Kesely 解决方案以在字典理解中使用 Walrus 运算符

out = {p[0]:p[1] for subl in sof for tpl in subl if (p:=[t for t in tpl if t != ""])}
# out:
# {'ABC': '0702', 'CDF': '0702', 'XYZ': '0702'}