在Python中使用字典?

2024-05-16 17:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

theme =  {
           'ADV': ['RAF', 'WS', 'BJ']
           'BC': ['B', 'SS', 'S']
           'LS': ['WF', 'SS'] }

names = ['Dubai', 'India', 'Monacco']

all_themes = {
                'Dubai': {'RAF', 'B'}
                'India': {'WF', 'SS'}
              }

输出:

{
  'Dubai': ['ADV', 'BC']
  'India': ['IS', 'BC']
  'Monacco': []
 }

遍历列表名称,逐个检查所有主题键(城市),如果主题键值中存在任何一个值,则将城市分配给主题中的相应键。 作为参考,检查输出。你知道吗


Tags: 主题wsnamesallthemesslsraf
1条回答
网友
1楼 · 发布于 2024-05-16 17:41:51

对输入进行消毒后:

theme =  {'ADV': ['RAF', 'WS', 'BJ'],
          'BC': ['B', 'SS', 'S'],
          'LS': ['WF', 'SS']}

names = ['Dubai', 'India', 'Monacco']

all_themes = {'Dubai': {'RAF', 'B'},
              'India': {'WF', 'SS'}}

你可以这样写一本方便的词典:

res = {k: [k_ for k_, v_ in theme.items() if any(x in v_ for x in all_themes.get(k, []))] for k in names}

产生:

{'Dubai': ['ADV', 'BC'], 'India': ['BC', 'LS'], 'Monacco': []}

理解细节:

{k: <value> for k in names}

到目前为止还不错,但是<value>应该是什么呢?。。你知道吗

Check the all_themes key(city) one by one, if any one of the value is present in theme's key values, assign the city to the respective key from the theme's.

又名:

一个theme键的列表,在相应的all_themes值中至少可以找到它们所包含的一个值。所以:

[k_ for k_, v_ in theme.items() if any(x in sub_v for x in all_themes.get(k, []))]

相关问题 更多 >