简体   繁体   English

创建列表字典的 Pythonic 方法(字典理解)

[英]Pythonic way to create a dictionary of lists (dict comprehension)

I have the following list:我有以下列表:

files = ['AAA_1', 'BBB_2', 'CCC_1', 'AAA_2', 'BBB_4']

And I have the following dict:我有以下听写:

dict = {
     'AAA' : [],
     'BBB': [],
     'CCC' : []
}

My expected output is:我的预期输出是:

dict = {
     'AAA' : ['AAA_1', 'AAA_2'],
     'BBB': ['BBB_2', 'BBB_4'],
     'CCC' : ['CCC_1']
}

I was able to achieve this using:我能够使用以下方法实现这一目标:

for file in files:
    if file.startswith(file[:-2]):
        dict[file[:-2]].append(file)

If I use:如果我使用:

dict = {file[:-2]: [file] for file in files if file.startswith(file[:-2])}

I got:我有:

{'AAA': ['AAA_2'], 'BBB': ['BBB_4'], 'CCC': ['CCC_1']}

My doubt is: How can I append values in a dictionary of lists using dict comprehension?我的疑问是:如何使用字典理解在列表字典中附加值?

I would not recommend using a dictionary comprehension, as a simple for-loop structure is much more readable.我不建议使用字典理解,因为简单的 for 循环结构更具可读性。 But if you must have one, here you go:但如果你必须有一个,你去:

sorted_files = {f[:-2] : [file for file in files if file.startswith(f[:-2])] for f in files}

Also, I do not recommend using Python keywords as variable names.另外,我不建议使用 Python 关键字作为变量名。 It is bad practice, and sometimes you may confuse the program.这是不好的做法,有时您可能会混淆程序。

Output:输出:

{'AAA': ['AAA_1', 'AAA_2'], 'BBB': ['BBB_2', 'BBB_4'], 'CCC': ['CCC_1']}

你可以用这样的两个嵌套推导来做到这一点:

dict = {key: [file for file in files if file[:-2] == key] for key in dict}

If you want to do this purely with comprehensions, you need an inner list comprehension that builds the entire list for a given prefix, and you probably want another comprehension to build the set of prefixes/keys (although this isn't strictly necessary since you can regenerate each entry multiple times and it'll just overwrite itself):如果你想纯粹用推导来做到这一点,你需要一个内部列表推导来为给定的前缀构建整个列表,并且你可能需要另一个推导来构建前缀/键集(尽管这不是绝对必要的,因为你可以多次重新生成每个条目,它只会覆盖自己):

>>> files = ['AAA_1', 'BBB_2', 'CCC_1', 'AAA_2', 'BBB_4']
>>> {k: [f for f in files if f.startswith(k)] for k in {f[:3] for f in files}}
{'BBB': ['BBB_2', 'BBB_4'], 'AAA': ['AAA_1', 'AAA_2'], 'CCC': ['CCC_1']}

Note that in addition to being a little less legible, it's less efficient because you need to iterate over files in its entirety for each entry.请注意,除了不太易读之外,它的效率也较低,因为您需要为每个条目遍历整个files Using a loop that iterates over files once is the method I'd use.使用循环遍历files一次是我将使用的方法。

All you need is to use nested comprehension:您只需要使用嵌套理解:

dict_ = {
    file_group[:-2]: [file for file in files if file.startswith(file_group[:-2])] for file_group in files}

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

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