data =
{'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'},
{'name': 'emerald', 'colour': 'green', 'month': 'May'},
{'name': "cat's eye", 'colour': 'yellow', 'month': 'June'},
{'name': 'sardonyx', 'colour': 'red', 'month': 'August'},
{'name': 'peridot', 'colour': 'green', 'month': 'September'},
{'name': 'ruby', 'colour': 'red', 'month': 'December'}]}
如何創建顏色串列,然后只找到紅色的月份?
我已經嘗試過,如果,但我不斷收到錯誤訊息
字串索引必須是整數
uj5u.com熱心網友回復:
因為您在串列中有字典,所以您可以使用帶有嵌套 if 邏輯的串列理解來過濾掉那些您不想要的值:
[x['month'] for x in data['gems'] if x['colour'] == 'red']
回報:
['January', 'August', 'December']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/532896.html
