gpt4 book ai didi

python - 根据单独的字典有条件地创建字典

转载 作者:行者123 更新时间:2023-12-01 06:45:33 24 4
gpt4 key购买 nike

我发现了类似的问题,但大多数是针对 Python 2 及更早版本的。

我有一列包含 5000 多个值,我正在用它创建一个字典。我想列出一些包含某些单词的行,如果值不包含它,它将被保存到“其他”。

我已完成以下操作:

my_groups = {
'Group 1' : r'utilities|cleaning',
'Group 2' : r'cooking|kitchen',
'Group 3' : r'decorations|planning',
'Group 4' : r'conceirge|guest|information|attendants',
#...there are 300 groups in the dataset
}

但是由于数据太大,我需要将组分为两类:前线后门。我能做到:

group_cat = {
'Frontline' : r'conceirge|guest|information|attendants|waiter|MC',
'Backdoor' : r'utilities|cleaning|cooking|kitchen|chef|event|decorations|planning',
#...there are 300 groups in the dataset
}

但是这个列表会很长,因为大约有 300 个具有不同描述的组。有没有一种方法可以让我只指定第一个并在另一个中自动分配其他其他?

#something like this
group_cat = {
'Frontline' : r'conceirge|guest|information|attendants|waiter|MC',
'Backdoor' : r'OTHER_KEYWORDS_HERE',
}

最佳答案

如果我正确理解了这个问题,下面的代码应该可以工作:

代码:

my_groups = {
'Group 1' : r'utilities|cleaning',
'Group 2' : r'cooking|kitchen',
'Group 3' : r'decorations|planning',
'Group 4' : r'conceirge|guest|information|attendants',
}

group_cat = {
'Frontline' : r'conceirge|guest|information|attendants|waiter|MC'
}

group_cat['Backdoor'] = '|'.join(set(x
for val in my_groups.values()
for x in val.split('|')
if x not in group_cat['Frontline'])
)

输出:

>>> group_cat
{'Frontline': 'conceirge|guest|information|attendants|waiter|MC',
'Backdoor': 'cooking|utilities|planning|cleaning|decorations|kitchen'}

关于python - 根据单独的字典有条件地创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com