<p>你可以使用<a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehensions</a>!你知道吗</p>
<blockquote>
<p>List comprehensions provide a concise way to create lists. Common
applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or
iterable, or to create a subsequence of those elements that satisfy a
certain condition.</p>
</blockquote>
<p>对于状态中的每个s,对于每个字符,检查它是否出现在字母列表中。如果找到了,那么您可以在不丢失其顺序的情况下获取列表中的索引和字符!你知道吗</p>
<pre><code>>>> [(s,[(index,c) for index,c in enumerate(s) if c in letters]) for s in states]
[('minnesota', [(4, 'e'), (8, 'a')]), ('new york', [(1, 'e')]), ('florida', [(5, 'd'), (6, 'a')])]
</code></pre>
<p>如果你把清单分解</p>
<pre><code>>>> [s for s in states]
['minnesota', 'new york', 'florida']
>>> [[c for index,c in enumerate(s)] for s in states]
[['m', 'i', 'n', 'n', 'e', 's', 'o', 't', 'a'], ['n', 'e', 'w', ' ', 'y', 'o', 'r', 'k'], ['f', 'l', 'o', 'r', 'i', 'd', 'a']]
>>> [[(index,c) for index,c in enumerate(s)] for s in states]
[[(0, 'm'), (1, 'i'), (2, 'n'), (3, 'n'), (4, 'e'), (5, 's'), (6, 'o'), (7, 't'), (8, 'a')], [(0, 'n'), (1, 'e'), (2, 'w'), (3, ' '), (4, 'y'), (5, 'o'), (6, 'r'), (7, 'k')], [(0, 'f'), (1, 'l'), (2, 'o'), (3, 'r'), (4, 'i'), (5, 'd'), (6, 'a')]]
>>> [(s,[(index,c) for index,c in enumerate(s)]) for s in states]
[('minnesota', [(0, 'm'), (1, 'i'), (2, 'n'), (3, 'n'), (4, 'e'), (5, 's'), (6, 'o'), (7, 't'), (8, 'a')]), ('new york', [(0, 'n'), (1, 'e'), (2, 'w'), (3, ' '), (4, 'y'), (5, 'o'), (6, 'r'), (7, 'k')]), ('florida', [(0, 'f'), (1, 'l'), (2, 'o'), (3, 'r'), (4, 'i'), (5, 'd'), (6, 'a')])]
</code></pre>
<p>为了使元素的访问更容易,你可以使用dict理解!你知道吗</p>
<pre><code>>>>res = {s:[(index,c) for index,c in enumerate(s) if c in letters] for s in states}
>>> print res
{'minnesota': [(4, 'e'), (8, 'a')], 'new york':[(1, 'e')], 'florida':[(5, 'd'), (6, 'a')]}
</code></pre>
<p>所以当你想进入一个州时,说“佛罗里达”</p>
<pre><code>>>> print res['florida']
[(5, 'd'), (6, 'a')]
</code></pre>
<p>希望有帮助!你知道吗</p>