【发布时间】:2020-10-15 13:37:47
【问题描述】:
我有一个相对简单的问题,可以通过 setdefault 轻松解决,但我现在正在自学理解,不知道如何通过理解来解决。
假设我有一个嵌套列表,其中一些内部列表具有相同的键。这意味着我应该能够生成一些键具有多个值的字典。我一直在尝试以某种方式附加这些值,但每次它只返回最后一个数字值,否则会出错。
这是一个例子:
>>> strlist
['hello w', 'hello', 'hello c', 'hello c c', 'dog']
>>> [[k,v] for k in set(sum([x.split() for x in strlist],[])) for v,x in enumerate(strlist) if k in x]
[['hello', 0], ['hello', 1], ['hello', 2], ['hello', 3], ['w', 0], ['c', 2], ['c', 3], ['dog', 4]]
我还尝试了一个元组列表、一个元组元组、一组列表、一组元组等。仍然无法让它与理解一起工作。
以下是一些失败的尝试:
>>> dict([(k,v) for k in set(sum([x.split() for x in strlist],[])) for v,x in enumerate(strlist) if k in x])
{'hello': 3, 'w': 0, 'c': 3, 'dog': 4}
>>> {k:k[v] for k,v in [[k,v] for k in set(sum([x.split() for x in strlist],[])) for v,x in enumerate(strlist) if k in x]}
Traceback (most recent call last):
File "<pyshell#285>", line 1, in <module>
{k:k[v] for k,v in [[k,v] for k in set(sum([x.split() for x in strlist],[])) for v,x in enumerate(strlist) if k in x]}
File "<pyshell#285>", line 1, in <dictcomp>
{k:k[v] for k,v in [[k,v] for k in set(sum([x.split() for x in strlist],[])) for v,x in enumerate(strlist) if k in x]}
IndexError: string index out of range
>>> {k:{v} for k,v in [[k,v] for k in set(sum([x.split() for x in strlist],[])) for v,x in enumerate(strlist) if k in x]}
{'hello': {3}, 'w': {0}, 'c': {3}, 'dog': {4}}
我们的目标是:
>>> {'hello': {0, 1, 2, 3], 'w': {0}, 'c': {2, 3}, 'dog': {4}}
这甚至可以通过理解实现,还是我必须使用更常见的传统循环方法之一?
【问题讨论】:
-
什么是
strlist? -
>>> strlist = ['hello w', 'hello', 'hello c', 'hello c c', 'dog'] -
一行一行是强迫症吗?
-
是的,但只是出于好奇,因为我正在学习 dict-comprehensions。
标签: python loops nested list-comprehension dictionary-comprehension