![](/img/trans.png)
[英]Flatten list of lists within dictionary values before processing in Pandas
[英]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
你犯了兩個錯誤:
flatten(v)
代替flatten(k)
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.