python 在列表解析中解包值的Walrus

wydwbb8l  于 2022-10-30  发布在  Python
关注(0)|答案(2)|浏览(147)

我有一个嵌套的列表,用一个元组作为关键字,把字典作为Map表。我正在努力把字典一起zip,这样它就可以通过Pandas导出到csv文件:

l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]

def dynDictCombiner(item):
    # would lambda be faster?
    def _combine(item):
        key = item.keys()[0]
        return key, item[key]

    col_keys = ('start', 'stop')
    row_keys = ('value')

    # syntax error
    l = [dict(zip(col_keys + row_keys, k + v)) for ((k, v) :=_combine(item) in l)]
    print(l)

l = dynDictCombiner(l)

# import pandas as pd

# df = pd.DataFrame.from_dict(l)

# print(df.shape)

# print(df)

# df.to_csv(path_or_buf='C:/temp/foo.csv', index=False, header=True)

预期输出:

[
{'start': 'A', 'stop': 'B', 'value': 1},
{'start': 'A', 'stop': 'C', 'value': 2},
{'start': 'A', 'stop': 'D', 'value': 3}
]

编辑,不带walrus的功能:

def dynDictCombinerSimple(items):
    # would lambda be faster?
    def _combine(item):
        key = list(item.keys())[0]
        return key, (item[key], )

    col_keys = ('start', 'stop')
    row_keys = ('value', )

    result = []
    for item in items:
        k, v = _combine(item)
        result.append(dict(zip(col_keys + row_keys, k + v)))
    print(result)

果然出来了:

[{'start': 'A', 'stop': 'B', 'value': 1}, {'start': 'A', 'stop': 'C', 'value': 2}, {'start': 'A', 'stop': 'D', 'value': 3}]
dgenwo3n

dgenwo3n1#

您不需要海象操作员来执行此操作:

l = [{('A', 'B'): 1}, {('A', 'C'): 2}, {('A', 'D'): 3}]

output= [{'start': start, 'stop': stop, 'value': value}
         for dct in l
         for (start, stop), value in dct.items()]

print(output)

# [{'start': 'A', 'stop': 'B', 'value': 1},

# {'start': 'A', 'stop': 'C', 'value': 2},

# {'start': 'A', 'stop': 'D', 'value': 3}]
h7wcgrx3

h7wcgrx32#

@MafMal:请把所有相关信息都加到问题前面,这样更容易理解,现在最相关的信息都在评论里。
我对你问题的回答是这样解释的:

l2 = [
    # rows are dicts as mentioned in the comments
    {
        ('A', 'B', 'C'): {
            'foo': 'bar1'
        }
    }, {
        ('A', 'C', 'D'): {
            'foo': 'bar2'
        }
    }, {
        ('A', 'D', 'E'): {
            'foo': 'bar3'
        }
    }
]

def genericDictCombiner(items, col_keys=('start', 'stop')):
    result = []
    for item in items:
        # As there is just one key/value pair, 
        # possibly that's why you came up with that _combine thing!
        for k, v in item.items():
            resDct = dict(zip(col_keys, k))
            resDct.update(v)
            result.append(resDct)
    return result

l = genericDictCombiner(l2)
print(l)

输出:

[{'start': 'A', 'stop': 'B', 'foo': 'bar1'}, {'start': 'A', 'stop': 'C', 'foo': 'bar2'}, {'start': 'A', 'stop': 'D', 'foo': 'bar3'}]

相关问题