python - 根据单独的字典有条件地创建字典
问题描述
我发现了类似的问题,但大多数是针对 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'}
推荐阅读
- react-native - 每“x”时间调用一次 API 的好方法是什么?
- java - 当我给它 1024m 时,JVM 得到 -Xmx512m
- r - 如何在 R 中使用 F 字符串将日期保存为 xlsl
- c# - 如何使用 VBA 从 C# 应用程序表单中自动选择值?
- talend - 在 Ubuntu-18.04 上安装 Talend Administration Center-7.3.1 时出错
- python - 这是运行容器/ROS的正确方法吗?
- powerbi - Dax Possion Dist 功能减少使用的措施数量
- laravel - 发生异常时有条件地重试作业
- macos - 适用于 macOS 的 SwiftUI 3.0:如何将 .frame 设置为以最大屏幕空间打开
- c# - 将字符串转换为 GSM