我需要在屏幕上显示列表。具有在中,使用列表生成器基于它生成新列表其使负元件加倍。将新列表输出到屏幕第一个列表输出正常,没有任何问题。但是我在显示第二个列表时有一个错误。
import random
c = 0
x = [ (random.randint (-50, 50) ) for c in range (20)]
print ('First list:', x)
y = [x * 2 (random.randint (-50, 50) ) for c in range (20) if x < 0]
print ('Second list:', y )
您可以使用if语句只过滤要加倍的负元素:
from random import randint
x = [randint(-50, 50) for _ in range(20)]
print(f'{x = }')
# If you want to keep only the doubled negative elements
y = [n * 2 for n in x if n < 0]
print(f'{y = }')
# If you want to keep the non negative elements as well you can use an if-else
z = [n * 2 if n < 0 else n for n in x]
print(f'{z = }')
示例输出:
x = [-2, -31, 35, -3, -34, 47, 28, 34, -18, 26, -25, -48, 18, -30, 1, 48, 43, -29, -30, -22]
y = [-4, -62, -6, -68, -36, -50, -96, -60, -58, -60, -44]
z = [-4, -62, 35, -6, -68, 47, 28, 34, -36, 26, -50, -96, 18, -60, 1, 48, 43, -58, -60, -44]
y = [x * 2 (random.randint (-50, 50) ) for c in range (20) if x < 0]
错误出现在代码的这一部分:
[x * 2 (random.randint (-50, 50) ) ...
您还有一个不匹配的)
。
也许你的意思是这样的?
y = [c * 2 for c in range(20)]
z = [random.randint(-50, 50) * c for c in y]
如果你想过滤double
和negative
元素,你可以这样做:
z = [element for element in y if (element < 0 and isinstance(element, float)]