3

字符串列表:

['Georgie Porgie', 87, '$$$', ['Canadian', 'Pub Food'], 'Queen St. Cafe', 82, '$', ['Malaysian', 'Thai'], 'Dumplings R Us', 71, '$', 'Chinese', 'Mexican Grill', 85, '$$', 'Mexican', 'Deep Fried Everything', 52, '$', 'Pub Food']

我正在尝试从上面的列表中创建一个 food_to_names 字典。这些美食在索引 3 中,有时是它们自己的迷你列表。餐厅名称位于索引 0。它们每四个索引重复一次。美食 - 3::4,名称 - 0::4。

我遇到的问题是从索引 3::4 中提取元素并将它们设为键。我认为问题来了,因为有时它们是字符串的迷你列表,有时它们只是一个字符串。这使得使用 defaultdict 对我来说很困难,但我对学习该功能很陌生。我看到其他一些答案包括 setdefault 之类的东西,但我不知道如何在这种特定情况下使用它。任何指导将不胜感激!

我想要这个输出:

Cuisine to list of restaurant names:
# dict of {str, list of str}
{'Canadian': ['Georgie Porgie'],
 'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],
 'Malaysian': ['Queen St. Cafe'],
 'Thai': ['Queen St. Cafe'],
 'Chinese': ['Dumplings R Us'],
 'Mexican': ['Mexican Grill']}

我试过这个并得到 TypeError: unhashable type: 'list':

from collections import defaultdict

cuisine_to_name = defaultdict(list)
for cuisine, name in zip(contents_list_2[3::4], contents_list_2[::4]):
  cuisine_to_name[cuisine].append(name)

print(cuisine_to_name)
4

2 回答 2

6

问题是变量美食是一个列表,而您正试图将其用作字典的键,请改为执行以下操作:

import pprint
from collections import defaultdict

data = ['Georgie Porgie', 87, '$$$', ['Canadian', 'Pub Food'],
        'Queen St. Cafe', 82, '$', ['Malaysian', 'Thai'],
        'Dumplings R Us', 71, '$', 'Chinese',
        'Mexican Grill', 85, '$$', 'Mexican',
        'Deep Fried Everything', 52, '$', 'Pub Food']

res = defaultdict(list)
for v, k in zip(data[::4], data[3::4]):
    ks = k if isinstance(k, list) else [k]
    for ki in ks:
        res[ki].append(v)

pprint.pprint(dict(res))

输出

{'Canadian': ['Georgie Porgie'],
 'Chinese': ['Dumplings R Us'],
 'Malaysian': ['Queen St. Cafe'],
 'Mexican': ['Mexican Grill'],
 'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],
 'Thai': ['Queen St. Cafe']}
于 2020-12-21T18:55:13.443 回答
0

如果 l 是您的列表,您可以执行以下操作:

l=['Georgie Porgie', 87, '$$$', ['Canadian', 'Pub Food'],
   'Queen St. Cafe', 82, '$', ['Malaysian', 'Thai'],
   'Dumplings R Us', 71, '$', 'Chinese',
   'Mexican Grill', 85, '$$', 'Mexican',
   'Deep Fried Everything', 52, '$', 'Pub Food']

res={l[i]:l[i+3] if type(l[i+3])==list else [l[i+3]]  for i in range(0,len(l),4)}

>>>print(res)

{'Georgie Porgie': ['Canadian', 'Pub Food'], 'Queen St. Cafe': ['Malaysian', 'Thai'], 'Dumplings R Us': ['Chinese'], 'Mexican Grill': ['Mexican'], 'Deep Fried Everything': ['Pub Food']}
于 2020-12-21T19:54:09.723 回答