简体   繁体   中英

Can anyone tell me what is wrong with this list comprehension?

I'm just learning how to do list comprehensions. I was given this question:

Given a list of numbers, return the list with all even numbers doubled, and all odd numbers turned negative.

>>input_list=[72, 26, 79, 70, 20, 68, 43, -71, 71, -2]

Here is the code I wrote, but I'm not sure why I'm getting a "bad input" error:

output_list = [i * -1 if i < 0 if i%2==1 else i * 2 for i in input_list]

Can anyone tell me what is wrong with my code?

I am assuming you don't want to change the number at all if it is an odd negative number:

output_l = [x*2 if x % 2 == 0 else x*-1 if x > 0 else x for x in input_list]

The key here is to use two conditionals within the list comprehension. The first will check whether to double the number (if even number) and the second will check whether to negate the number (if it is odd and positive) or remain as it is if already negative.

Remember that you cannot add two if statements sequentially. You have to define an else in between.

Try this Instead

input_list = [72,26,79,70,20,68,43,-71,71,-2]
output_list=[ x*2 if x%2==0 else -1*abs(x) for x in  input_list]
print(output_list)

or:[false,true][condition] is the syntax:

input_list = [72,26,79,70,20,68,43,-71,71,-2]
output_list=[[-1*abs(x),x*2] [x%2==0] for x in  input_list]
print(input_list)
print(output_list)

Your answer was given in this question: if/else in a list comprehension?

input_list = [72, 26, 79, 70, 20, 68, 43, -71, 71, -2]
output_list = [i*2 if i % 2 == 0 else abs(i) * -1 for i in input_list]
print(output_list)

If you are using if and else this is how to format it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM