簡體   English   中英

難以理解列表理解

[英]Having trouble with being selective in list comprehension

我需要使用列表推導將列表中的某些項目從攝氏溫度轉換為華氏溫度。 我有溫度清單。 我現在最好的猜測是這樣的:

good_temps = [c_to_f(temp) for temp in temperatures if 9 < temperatures[temp] <32.6]

但是,我做的事情不正確,我無法弄清楚。

另一種答案指出的替代解決方案是使用過濾器來獲取子集:

filter(lambda temp: 9 < temp < 32.6, temperatures)

然后進行列表理解以進行轉換:

[c_to_f(temp) for temp in temperatures] 

最終表達:

good_temps = [c_to_f(temp) for temp in filter(lambda t: 9 < t < 32.6, temperatures)]

你很親密 您需要的是:

good_temps = [c_to_f(temp) for temp in temperatures if 9 < temp < 32.6]

該代碼僅在大於9且小於32.6的情況temp才轉換temp 對於超出該范圍的temp值,不會將任何值添加到good_temps

temp已經是來自temperatures的項,因此temperatures[temp]並沒有多大意義,因為它試圖將temperatures項用作索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM