<p>如果使用<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">Dictionary</a>和<a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">List Comprehension</a>,这实际上非常简单。您可以在一行中获得所需的输出。你知道吗</p>
<pre><code>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)
</code></pre>
<p>可读性更强但理解力更强</p>
<pre><code>d2={stop:[route for route in d1.keys() if stop in d1[route]] for stop_list in d1.values() for stop in stop_list}
</code></pre>
<p>输出:</p>
<pre><code>{'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']}
</code></pre>