Python 删除字典中不必要的列表括号

Python 删除字典中不必要的列表括号,python,list,python-3.x,dictionary,Python,List,Python 3.x,Dictionary,我有这本字典: n ={'b': [['a'], ['c']], 'a': [['c', 'b'], ['c']], 'c': [['b']]} 并需要以下输出: n ={'b': ['a', 'c'], 'a': ['c', 'b'], 'c': ['b']} 我试图使用itertools和join,但无法使其正常工作,有人能帮忙吗?我会重复dict并忽略不相关的列表 为了唯一性,您可以将每个内部列表强制转换为一个集合 n ={'b': [['a', 'b'], ['c']], 'a':

我有这本字典:

n ={'b': [['a'], ['c']], 'a': [['c', 'b'], ['c']], 'c': [['b']]}
并需要以下输出:

n ={'b': ['a', 'c'], 'a': ['c', 'b'], 'c': ['b']}

我试图使用
itertools
join
,但无法使其正常工作,有人能帮忙吗?

我会重复dict并忽略不相关的列表

为了唯一性,您可以将每个内部列表强制转换为一个
集合

n ={'b': [['a', 'b'], ['c']], 'a': [['c', 'b'], ['c']], 'c': [['b']]}

new_n = {}

for k,v in n.items():
  n[k] = [inner_item for item in v for inner_item in item]

print (n)
您可以尝试以下方法:

from itertools import chain

n ={'b': [['a'], ['c']], 'a': [['c', 'b'], ['c']], 'c': [['b']]}

new_n = {a:list(set(chain(*[i[0] if len(i) == 1 else i for i in b]))) for a, b in n.items()}
输出:

{'a': ['c', 'b'], 'c': ['b'], 'b': ['a', 'c']}

具有
总和的解决方案

>>> {k: sum(v, []) for k, v in n.items()}
{'a': ['c', 'b', 'c'], 'b': ['a', 'c'], 'c': ['b']}
返回一个“开始”值(默认值:0)加上一组数字的总和

因此,使用空列表作为起始值是有效的

在不保留顺序的情况下使用
set
删除乘法:

>>> {k: list(set(sum(v, []))) for k, v in n.items()}
{'a': ['c', 'b'], 'b': ['a', 'c'], 'c': ['b']}
只需使用from
itertools
,即可组合这些工具:

from itertools import chain

from_it = chain.from_iterable
{k: list(from_it(i)) for k, i in n.items()}
如果您需要列表中的唯一值(根据您不需要的标题),您还可以将
from\u it
的结果包装到
集合中

解决这一问题的单衬里解决方案(不推荐):

{key: list(set([item for subarr in value for item in subarr])) for key, value in n.items()}
不过,阅读起来要困难得多。如果您真的不想导入任何内容,可以编写一个helper函数

def flat_and_unique_list(list_of_lists):
    return list(set([item for sub_list in list_of_lists for item in sub_list]))

{key: flat_and_unique_list(value) for key, value in n.items()}
{k:list(set(chain.from_iterable(i)))表示k,i in n.items()}
如果需要唯一值,或者
{k:list(chain.from_iterable(i))表示k,i in n.items()}
如果不需要。
def flat_and_unique_list(list_of_lists):
    return list(set([item for sub_list in list_of_lists for item in sub_list]))

{key: flat_and_unique_list(value) for key, value in n.items()}