还是没有搞懂这个结构
Topic source问:分析一下这个表达式"l_01 = [x if x%2==0 -x else abs(x) for x in range(-6,5)]"
这是GPT的回答,原来我被误导了:
这个表达式是一个列表表达式,它在range(-6, 5)
这个范围内遍历了所有整数,根据条件将每个整数放入列表中。
在这个列表表达式中,x
代表range(-6,5)
内的每个整数。如果这个整数x
可以被2整除,则将x
加入列表l_01
中;否则,将x
的绝对值加入到列表l_01
中。如果x
是奇数,则在条件表达式中使用减号将其变为负数。
因此,当表达式执行完成时,l_01
的值为[6, -5, 4, -3, 2, -1, 0, 1, 2, 3]
。
问:the difference bettwen "l_02 = [x if x % 2 == 0 - x else abs(x) for x in range(-6, 5)]" and"l_03 = [x if x % 2 == 0 else abs(x) for x in range(-6, 5)]"
这是Bard的回答:
The difference between the two formulas is the expression that is evaluated for the even numbers. In the first formula, the expression is x if x % 2 == 0 - x
. This expression subtracts the number from itself if it is even. In the second formula, the expression is x if x % 2 == 0
. This expression simply returns the number if it is even.
As a result, the first formula will subtract even numbers from themselves, while the second formula will simply return even numbers.
Here is an example of the output of the two formulas:
l_02 = [x if x % 2 == 0 - x else abs(x) for x in range(-6, 5)]
print(l_02)
l_03 = [x if x % 2 == 0 else abs(x) for x in range(-6, 5)]
print(l_03)
Output:
[6, 5, 4, 3, 2, -1, 0, 1, 2, 3, 4]
[6, 5, 4, 3, 2, 0, 1, 2, 3, 4]
- 1
緣定さんせぃ様
l_02 = [x if x%2==0 -x else abs(x) for x in range(-6,5)]
print(l_02)
奇数直接绝对值,偶数取加负号
[6, 5, 4, 3, 2, -1, 0, 1, 2, 3, 4]
我有点懵了,在第一个判断后面再加一个执行语句为啥会这样