[英]How to create a list of values in a dictionary comprehension in Python
Taking a very simple example of looping over a sentence and creating a dictionary which maps {x:y}
, where x
is a key representing the length of the words and y
is a list of words in the sentence that contain x
amount of letters举一个非常简单的例子,循环一个句子并创建一个映射{x:y}
的字典,其中x
是表示单词长度的键, y
是句子中包含x
个字母的单词列表
Input:输入:
mywords = "May your coffee be strong and your Monday be short"
Expected Output:预计 Output:
{2: ['be', 'be'], 3: ['May', 'and'], 4: ['your', 'your'], 5: ['short'], 6: ['coffee', 'strong', 'Monday']}
Here's an attempt that creates a list of values but overwrites it each time:这是创建值列表但每次都覆盖它的尝试:
{len(x):[x] for x in mywords.split()}
{2: ['be'], 3: ['and'], 4: ['your'], 5: ['short'], 6: ['Monday']}
Is it possible to do this in one line in Python?是否可以在 Python 中一行完成此操作?
Sure, you can, using sorted
+ groupby
, but it doesn't look great. 当然可以,您可以使用sorted
+ groupby
,但这看起来并不好。
from itertools import groupby
d = dict([(k, list(g)) for k, g in groupby(sorted(mywords.split(), key=len), key=len)])
print(d)
{2: ['be', 'be'],
3: ['May', 'and'],
4: ['your', 'your'],
5: ['short'],
6: ['coffee', 'strong', 'Monday']}
PS, Here's my answer (using defaultdict
that I recommend over this) to the original question . PS,这是我对原始问题的答案 (使用我建议的defaultdict
)。
Don't try to cram everything in one line, it won't be readable. 不要试图将所有内容都塞进一行,因为它不会可读。 This is a simple, easy-to-understand solution, even if it takes a couple of lines: 这是一个简单,易于理解的解决方案,即使它需要两行代码:
from collections import defaultdict
mywords = "May your coffee be strong and your Monday be short"
ans = defaultdict(list)
for word in mywords.split():
ans[len(word)].append(word)
It is possible to use a regular expression by build a raw string from 1 to the max length of the word then use the groups and iterate their position as a the size of the word.可以通过构建从 1 到单词的最大长度的原始字符串来使用正则表达式,然后使用这些组并将它们的 position 迭代为单词的大小。 Lastly using a defaultdict as set add the words from the group to the dictionary.最后使用 defaultdict as set 将组中的单词添加到字典中。
text = "May your hot chocolate be delicious and sweet and your Monday be short"
max_len=0
for word in text.split():
if len(word)>max_len:
max_len=len(word)
pattern=[]
for index in range(1,max_len+1):
index=str(index)
pattern.append(r"(\b\w{"+"{index}".format(index=index)+r"}\b\s+)*")
pattern=''.join(pattern)
print(pattern)
groups=re.findall(pattern,text)
dict = defaultdict(set)
for group in groups:
for position,value in enumerate(group):
if len(value)>0:
dict[position+1].add(value)
print(dict)
output: output:
defaultdict(<class 'set'>, {3: {'May ', 'hot ', 'and '}, 4: {'your '}, 9: {'delicious ', 'chocolate '}, 2: {'be '}, 5: {'sweet '}, 6: {'Monday '}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.