回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>这里有两个(我认为)应该做同样的事情,但实际上没有。在</p>
<p>似乎在列表理解中,获取的索引是第一个可以对应的索引,因此,当您在不同的索引中有相同的值时,就会出现歧义。在</p>
<p>有没有方法可以修改<code>filter2</code>中的列表理解,从而得到与<code>filter1</code>中相同的结果?在</p>
<pre><code> L = [98.75011926342906,
97.8178200008178,
98.6138182016438,
98.55520874507613,
98.25262038791283,
98.75011926342906,
99.06770073738875,
98.66970163697574,
98.56611283001895,
98.47751713985852,
98.66970163697574,
97.8178200008178]
def filter1(L, threshold=98.7):
items = []
for i in range(len(L)):
if L[i] < threshold:
items.<a href="https://www.cnpython.com/list/append" class="inner-link">append</a>(i)
return items
def filter2(L, threshold=98.7):
items = [L.index(x) for x in L if x <= threshold]
return items
print filter1(L)
>>> [1, 2, 3, 4, 7, 8, 9, 10, 11]
print filter2(L)
>>> [1, 2, 3, 4, 7, 8, 9, 7, 1]
</code></pre>