<p>您可以将<code>items</code>子列表存储在字典中,按它们的第一个元素进行索引。你知道吗</p>
<pre><code>from random import shuffle
items = [
["e",None,None],
["pork","pork.png","meat"],
["beef","b.png","meat"],
["cheese","c.png","not"],
]
items_dict = {u[0]: u for u in items}
items_list = ["e","beef","pork","beef"]
shuffle(items_list)
for s in items_list:
print(s, items_dict[s])
</code></pre>
<p><strong>输出</strong></p>
<pre><code>beef ['beef', 'b.png', 'meat']
e ['e', None, None]
beef ['beef', 'b.png', 'meat']
pork ['pork', 'pork.png', 'meat']
</code></pre>
<hr/>
<p>要打印第二项(即PNG):</p>
<pre><code>for s in items_list:
print(s, items_dict[s][1])
</code></pre>
<p><strong>输出</strong></p>
<pre><code>e None
beef b.png
beef b.png
pork pork.png
</code></pre>
<hr/>
<p>这是相当有效的,因为没有创建新的列表:<code>items_dict</code>中的列表与<code>items</code>中的列表对象相同。因此,如果需要,可以通过<code>items</code>或<code>items_dict</code>对这些列表进行变异。你知道吗</p>
<pre><code>items_dict["cheese"].append("cheddar")
print(items[3])
items[0][2] = "something"
print(items_dict["e"])
</code></pre>
<p><strong>输出</strong></p>
<pre><code>['cheese', 'c.png', 'not', 'cheddar']
['e', None, 'something']
</code></pre>
<hr/>
<p>你不需要<em>这个<code>items_dict</code>,但是另一个选择是一个双<code>for</code>循环,如果<code>items</code>很大,它会变得非常<em>低效。你知道吗</p>
<pre><code>for s in items_list:
for seq in items:
if seq[0] == s:
print(s, seq)
break
</code></pre>
<p><strong>输出</strong></p>
<pre><code>beef ['beef', 'b.png', 'meat']
e ['e', None, None]
beef ['beef', 'b.png', 'meat']
pork ['pork', 'pork.png', 'meat']
</code></pre>