[英]Syntax Error for if statement in Lambda function
targetScore 是整數列表中的最大值。 我將 lambda function 與 map 一起使用。 對於 function 中的每個值,如果項目等於最大值,我希望 lambda 到 append 到列表“ListofIndices”。
當我嘗試定義:
getter = lambda x: listofIndices.append(index(x)) if x == targetScore
我收到錯誤聲明:
getter = lambda x: listofIndices.append(index(x)) if x == targetScore
SyntaxError: invalid syntax
聽起來您需要一個過濾器和一個 map,這需要兩個不同的功能:一個用於條件,一個用於轉換。 您可以使用列表推導來獲得相同的效果:
listOfIndices = [i for i, x in enumerate(integers) if x == targetScore]
enumerate
遍歷 (index, element) 對,因此您不必使用index
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.