[英]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.请记住,您不能顺序添加两个
if
语句。 You have to define an else
in between.您必须在两者之间定义一个
else
。
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: or:[false,true][condition] 是语法:
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?你的答案是在这个问题中给出的: 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.如果您使用 if 和 else 这是如何格式化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.