[英]One line conditional assignment if statement
這是我在此論壇上提出的第一個問題,因此,歡迎您提出寶貴意見,以使它對其他人更有用。
說我有這個清單:
IDs = ['First', 'Second', 'Third']
這本字典:
statistics = {('First', 'Name'):"FirstName", ('Second','Name'):"SecondName", ('Third','Name'):"ThirdName"}
是否有比以下更短,更容易閱讀的單線紙?
firstID = IDs[[statistics[ID,'Name'] for ID in IDs].index('FirstName')]
非常感謝
# If you ever plan to change the order of IDs:
firstID = IDs[IDs.index('First')]
# If you are literally just looking for the first ID in IDs:
firstID = IDs[0]
如果您在這兩行中查看代碼:
IDs = ['First', 'Second', 'Third']
firstID = IDs[[statistics[ID,'Name'] for ID in IDs].index('FirstName')]
您新創建的列表中的'FirstName'
索引將始終等於IDs
中'First'
的索引。 因為您的列表理解將按順序迭代IDs
並按順序排列相應的dict
值,所以您將始終在與IDs
出現'First'
相同的索引處創建'FirstName'
。 因此,使用上述方法之一簡單地從該列表中調用它會更加有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.