在list(map)中编写语法的正确方法是什么?

时间:2020-10-27 13:50:55

标签: python

目标是要有一个列表[1:11],其中每个小于5的数字都具有x-2。

lst = list[1,11]
lst
[1,2,3,4,5,6,7,8,9,10]

这就是我正在使用的。尝试过:

list(map(lambda x: x-2 for x<5 in lst, lst))
list(map(x-2, filter(lambda x: x<5 in lst))
list(if x < 5 in lst(map(lambda x: x-2)))

我对Python语法非常陌生。我在上面所做的尝试以及许多与这些类似的尝试导致了SyntaxError。很抱歉,如果我在描述问题时犯了错误,因为我也是Stack的新手。

2 个答案:

答案 0 :(得分:2)

可能的解决方案是:

solution = list(map(lambda x: x-2 if x < 5 else x, lst))

答案 1 :(得分:1)

这是一个可能的解决方案:

export class ProfileT1Component implements OnInit {
    
    userDetails:any;
    constructor(
        public profileService: ProfileServices){
          this.profileService.userDetails.subscribe((result)=>{
            console.log(result);
            this.userDetails=result;
            console.log("received user details in profile component constructor: ", this.userDetails);
          })
    
      }
    }

这是另一种可能的解决方案:

result = list(map(lambda x: x-2 if x<5 else x, lst))

这是您想要的输出(带有result = list(map(lambda x: x-2*(x<5), lst)) ):

lst = list(range(1, 11))