簡體   English   中英

使用列表列表展平字典值

[英]Flatten dictionary values with list of lists

我有包含鍵和值的 python 字典。 它的值都在一個列表中。 但是,其他元素可能在另一個列表中。 無論情況如何,我都只想返回一維平面列表。

例子:

sample_dict1 = 

defaultdict(list,
            {'File1.xlsx': ['Path/NEW/Subpath/File1.xlsx'],
'File2.xlsx': ['Path/NEW/Subpath/File2.xlsx'],
'File3.xlsx': ['Path/NEW/Subpath/File3.xlsx', ['Path/OLD/Subpath/File3.xlsx']],
'File4.xlsx': ['Path/NEW/Subpath/File4.xlsx', ['Path/OLD/Subpath/File4.xlsx'],
               ['Path/changed/Subpath/File4.xlsx']] } )


期望的輸出

output = 

defaultdict(list,
            {'File1.xlsx': ['Path/NEW/Subpath/File1.xlsx'],
'File2.xlsx': ['Path/NEW/Subpath/File2.xlsx'],
'File3.xlsx': ['Path/NEW/Subpath/File3.xlsx', 'Path/OLD/Subpath/File3.xlsx'],
'File4.xlsx': ['Path/NEW/Subpath/File4.xlsx', 'Path/OLD/Subpath/File4.xlsx',
               'Path/changed/Subpath/File4.xlsx'] } )



我的嘗試:


def flatten(xs):
    for x in xs:
        if isinstance(x, str):
            yield x
        elif isinstance(x, Iterable) and not isinstance(x, str):
            yield from flatten(x)

for k, v in sample_dict1.items():
        sample_dict1[k] = list(flatten(k])




來自問題Flatten list of lists in dictionary values before processing before Pandas

你犯了兩個錯誤:

  1. 使用flatten(v)代替flatten(k)
  2. 正確使用括號: list(flatten(v)) ì 而不是list(flatten(v])
def flatten(xs):
    for x in xs:
        if isinstance(x, str):
            yield x
        elif isinstance(x, Iterable) and not isinstance(x, str):
            yield from flatten(x)

for k, v in sample_dict1.items():
        sample_dict1[k] = list(flatten(v))

暫無
暫無

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

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