小编tcb*_*old的帖子

嵌套在Dict理解中的Python集合理解

我有一个元组列表,其中每个tuple包含一个string和一个数字形式:

[(string_1, num_a), (string_2, num_b), ...]
Run Code Online (Sandbox Code Playgroud)

字符串不是唯一的,数字也是如此,例如(string_1 , num_m)(string_9 , num_b)可能存在于列表中.

我正在尝试使用字符串作为键创建一个字典,并使用该字符串作为值创建一组所有数字:

dict = {string_1: {num_a, num_m}, string_2: {num_b}, ...}
Run Code Online (Sandbox Code Playgroud)

我已经成功地使用嵌套集合理解的以下字典理解:

#st_id_list = [(string_1, num_a), ...]
#st_dict = {string_1: {num_a, num_m}, ...} 
st_dict = {
    st[0]: set(
        st_[1]
        for st_ in st_id_list
        if st_[0] == st[0]
    )
    for st in st_id_list
}
Run Code Online (Sandbox Code Playgroud)

只有一个问题:st_id_list长达18,000个项目.这段代码运行500个元组的列表只需不到10秒,但运行完整的18,000个元组需要12分钟以上.我必须认为这是因为我在dict理解中嵌套了一套理解.

有没有办法避免这种情况,或者更聪明的方法呢?

python nested dictionary-comprehension set-comprehension

3
推荐指数
1
解决办法
589
查看次数