如何迭代和访问字典中的单个值

2024-06-01 01:01:26 发布

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

我正在做一些python的家庭作业,我被要求定义一个函数,它接受一个字典,将公交线路映射到公交车站,并返回一个字典,将公交车站映射到停靠在该车站的公交线路列表。输入如下:

{"Lentil": ["Chinook", "Orchard", "Valley", "Emerald","Providence",
"Stadium", "Main", "Arbor", "Sunnyside", "Fountain", "Crestview",
"Wheatland", "Walmart", "Bishop", "Derby", "Dilke"],
"Wheat": ["Chinook", "Orchard", "Valley", "Maple","Aspen", "TerreView",
"Clay", "Dismores", "Martin", "Bishop", "Walmart", "PorchLight",
"Campus"]}

我需要以某种方式将这些值做成键,同时检查这些值是否也是任何其他键中的值。基本上,我很难弄清楚如何访问这些值并使它们成为新的键(没有重复项),而不必对它们进行硬编码。你知道吗


Tags: 函数列表字典定义bishop家庭作业车站walmart
2条回答

如果使用DictionaryList Comprehension,这实际上非常简单。您可以在一行中获得所需的输出。你知道吗

d1={"Lentil": ["Chinook", "Orchard", "Valley", "Emerald","Providence",
"Stadium", "Main", "Arbor", "Sunnyside", "Fountain", "Crestview",
"Wheatland", "Walmart", "Bishop", "Derby", "Dilke"],
"Wheat": ["Chinook", "Orchard", "Valley", "Maple","Aspen", "TerreView",
"Clay", "Dismores", "Martin", "Bishop", "Walmart", "PorchLight",
"Campus"]}
d2={x:[y for y in d1.keys() if x in d1[y]] for l in d1.values() for x in l}
print(d2)

可读性更强但理解力更强

d2={stop:[route for route in d1.keys() if stop in d1[route]] for stop_list in d1.values() for stop in stop_list}

输出:

{'Chinook': ['Lentil', 'Wheat'], 'Orchard': ['Lentil', 'Wheat'], 'Valley': ['Lentil', 'Wheat'], 'Emerald': ['Lentil'], 'Providence': ['Lentil'], 'Stadium': ['Lentil'], 'Main': ['Lentil'], 'Arbor': ['Lentil'], 'Sunnyside': ['Lentil'], 'Fountain': ['Lentil'], 'Crestview': ['Lentil'], 'Wheatland': ['Lentil'], 'Walmart': ['Lentil', 'Wheat'], 'Bishop': ['Lentil', 'Wheat'], 'Derby': ['Lentil'], 'Dilke': ['Lentil'], 'Maple': ['Wheat'], 'Aspen': ['Wheat'], 'TerreView': ['Wheat'], 'Clay': ['Wheat'], 'Dismores': ['Wheat'], 'Martin': ['Wheat'], 'PorchLight': ['Wheat'], 'Campus': ['Wheat']}

如果我正确理解了这个问题,你想沿着路线找到站点,那里有同一辆巴士到访的站点,基本上是找到巴士路线的重复。你知道吗

请看下面的代码。你知道吗

bus_routes = {"Lentil": ["Chinook", "Orchard", "Valley", "Emerald","Providence", "Stadium", "Main", "Arbor", "Sunnyside", "Fountain", "Crestview", "Wheatland", "Walmart", "Bishop", "Derby", "Dilke"], "Wheat": ["Chinook", "Orchard", "Valley", "Maple","Aspen", "TerreView", "Clay", "Dismores", "Martin", "Bishop", "Walmart", "PorchLight", "Campus"]}
route_dup = {}
for x,y in bus_routes.items():
    for z in y:
        try:
            if route_dup[z]:
                route_dup[z].append(x)
        except KeyError:
            route_dup[z] = [x]

print(route_dup)

我们用bus_routes.items()迭代得到一个变量(y),其中x是路由名,y是停止名列表。然后,我们用y创建另一个迭代,并尝试查看具有该停止名称的键是否已经存在于route_dup中,如果它不存在,它将捕获KeyError,并使用列表中路由名称的值创建它,但是,如果该键确实存在,我们可以放心地说它将访问我们已经创建的列表,因此append(),使用下一个路由名称。你知道吗

希望这有帮助。你知道吗

相关问题 更多 >