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

时间:2017-07-03 15:46:53

标签: 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']}

我尝试使用itertoolsjoin,但无法让它发挥作用,任何人都可以帮忙吗?

5 个答案:

答案 0 :(得分:3)

只需使用itertools中的chain.from_iterable来组合这些:

from itertools import chain

from_it = chain.from_iterable
{k: list(from_it(i)) for k, i in n.items()}

如果您需要列表中的唯一值(根据您没有的标题),您还可以将from_it的结果包装在set中。

答案 1 :(得分:0)

我会迭代dict并忽略不相关的列表。

对于唯一性,您可以将每个inner_list转换为set

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)

答案 2 :(得分:0)

你可以试试这个:

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']}

答案 3 :(得分:0)

sum的解决方案:

>>> {k: sum(v, []) for k, v in n.items()}
{'a': ['c', 'b', 'c'], 'b': ['a', 'c'], 'c': ['b']}
sum(iterable, start=0, /)
     

返回'start'值的总和(默认值:0)加上可迭代的数字

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

使用set

删除使用而不保留顺序
>>> {k: list(set(sum(v, []))) for k, v in n.items()}
{'a': ['c', 'b'], 'b': ['a', 'c'], 'c': ['b']}

答案 4 :(得分:0)

对此的单线解决方案(并且不推荐)是:

{key: list(set([item for subarr in value for item in subarr])) for key, value 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()}
相关问题