<p>从列表或字典中提取信息有两种基本方法。第一个是一个简单的循环,用于查找所需的项。第二种理解可能更简洁、更具表现力,但并不总是清晰</p>
<p>如果一个列表中的字典实际上是分开的(多个字典组成[您称之为单个数据单元],那么循环解决方案可能是最容易理解的</p>
<p>在此假设每个数据单元始终有一对字典,其形式与问题中当前的形式相同:</p>
<pre class="lang-py prettyprint-override"><code>list_dicts = [
{'Symbol': 'KO', 'Code': 12345, 'Instrument': 'option'},
{'Strike': '50', 'Price': 3.95},
{'Symbol': 'KO', 'Code': 67890, 'Instrument': 'option'},
{'Strike': '51', 'Price': 6.19},
{'Symbol': 'KO', 'Code': 59684, 'Instrument': 'option'},
{'Strike': '52', 'Price': 7.58}
]
</code></pre>
<p>找到与给定罢工值匹配的所有价格和代码值的简单解决方案如下(在一个完整的程序中,您可以使用它):</p>
<pre class="lang-py prettyprint-override"><code>list_dicts = [
{'Symbol': 'KO', 'Code': 12345, 'Instrument': 'option'},
{'Strike': '50', 'Price': 3.95},
{'Symbol': 'KO', 'Code': 67890, 'Instrument': 'option'},
{'Strike': '51', 'Price': 6.19},
{'Symbol': 'KO', 'Code': 59684, 'Instrument': 'option'},
{'Strike': '52', 'Price': 7.58},
{'Symbol': 'KO', 'Code': 99999, 'Instrument': 'option'},
{'Strike': '51', 'Price': 9.99},
]
def getPriceCodeList(strike, db):
retList = []
for idx in range(0, len(db), 2):
if db[idx+1]["Strike"] == strike:
retList += [(db[idx+1]["Price"], db[idx]["Code"])]
return retList
print(getPriceCodeList('51', list_dicts))
</code></pre>
<p>这将返回所需数据的元组列表,例如罢工值为<code>51</code>:</p>
<pre class="lang-py prettyprint-override"><code>[(6.19, 67890), (9.99, 99999)]
</code></pre>