简体   繁体   English

使用列表理解的列表字典

[英]Dictionary of lists using list comprehension

I have a string (which I treat as a list of chars) and I'm trying via dictionary comprehension to create a dictionary with the keys of every char in the string and the values as a list of the indexes in which it appeared.我有一个字符串(我将其视为一个字符列表),我正在尝试通过字典理解来创建一个字典,其中包含字符串中每个字符的键以及作为它出现的索引列表的值。

For example:例如:

pattern = "abcdabccb"

desired dictionary:所需词典:

{'a' : [0,4], 'b' : [1,5,8], 'c':[2,6,7], 'd':[3]}

Best try so far:迄今为止最好的尝试:

{pattern[i]: [i] for i in range(0, len(pattern)) if pattern[i] != '_'}

returns only the last index where the char appeared.仅返回字符出现的最后一个索引。

Thanks in advance!提前致谢!

This is a fun question.这是一个有趣的问题。 You'll need a list-comprehension within a dict-comprehension:您需要在字典理解中进行列表理解:

>>> p = "abcdabccb"; # pattern
>>> {c: [i for i in range(len(p)) if p[i] == c] for c in p}
{'a': [0, 4], 'b': [1, 5, 8], 'c': [2, 6, 7], 'd': [3]}
>>> 

In plain words, here's what the comprehension says :简而言之,这就是理解所说的
Compose a dictionary by iterating over every character c in the pattern p .通过迭代模式p中的每个字符c来组成字典。 Use each c as the key, and let the corresponding value be the list of such indices i in p , where p[i] == c .使用每个c作为键,并让相应的值成为p中此类索引i的列表,其中p[i] == c

Instead of for c in p , you may use for c in set(p) to iterate over each character just once.您可以for c in set(p)而不是for c in p中的 for c 来迭代每个字符一次。

As @quamrana points out, you can always use a loop.正如@quamrana 指出的那样,您始终可以使用循环。 Here, a loop would be far more readable.在这里,循环会更具可读性。 But for honing your dict-comprehension chops, this is a pretty good practice problem.但是为了磨练你的听写理解能力,这是一个很好的练习题。

A dictionary comprehension should be used where map or filter might have been used.在可能使用mapfilter的地方应该使用字典理解。 The dict that you want is a summary of the input string.您想要的dict是输入字符串的摘要。

You just need to fall back on a plain for loop:你只需要回到一个普通的 for 循环:

from collections import defaultdict

pattern = "abcdabccb"
summary = defaultdict(list)

for idx,c in enumerate(pattern):
    summary[c].append(idx)

Output as required Output 根据需要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM