有没有一种方法可以在python中将列表作为单个变量读取
所以在前言中,我对python非常陌生(大约一周前开始)。我想测试一下我的技能,并创建一个程序,允许用户将一组数据输入到一个列表中,在这个列表中,数据将被排序并打印成一组正变量和负变量有没有一种方法可以在python中将列表作为单个变量读取,python,list,if-statement,Python,List,If Statement,所以在前言中,我对python非常陌生(大约一周前开始)。我想测试一下我的技能,并创建一个程序,允许用户将一组数据输入到一个列表中,在这个列表中,数据将被排序并打印成一组正变量和负变量 numbers = list(map(float, input( 'Enter numbers: \n').split())) positive_num=[] negative_num=[] for x in numbers: if numbers >0: positive_num.
numbers = list(map(float, input( 'Enter numbers: \n').split()))
positive_num=[]
negative_num=[]
for x in numbers:
if numbers >0:
positive_num.append(numbers)
elif numbers <0:
negative_num.appenend(numbers())
print('positive numbers: ' + positive_num)
print('negative numbers: ' + negative_num)
print("nuetral number: 0")
numbers=list(映射(float,输入('enternumbers:\n').split())
正数值=[]
负数_num=[]
对于数字中的x:
如果数字>0:
正数追加(数字)
elif数字0是一个变量,因此无法对两者进行比较。总而言之,我想问的问题是,我如何让列表中的每个变量与>或<相比进行测试,以便将其放入数组中
也许在这一点上我做错了所有的事情,我很迷茫。任何帮助和解释都将不胜感激。问题在于,在迭代列表时,x
指向列表中的每个项目,因此,您应该使用x
进行比较,而不是使用整个列表中的数字。同样,您还应该添加x
,而不是数字
for x in numbers:
if numbers >0:
positive_num.append(numbers)
elif numbers <0:
negative_num.appenend(numbers())
编号为x的:
如果数字>0:
正数追加(数字)
elif编号0:
正数追加(x)
elif x<0:
负数追加(x)
列表理解也很棒:
positive_num = [n for n in numbers if n > 0]
negitive_num = [n for n in numbers if n < 0]
positive_num=[n表示n,如果n>0,则n表示n]
负的数量=[n表示n,如果n<0,则n表示n]
尽管这里唯一的缺点是您实际上循环了两次但这里有一些可以修复错误的工作代码:
numbers = list(map(float, input( 'Enter numbers: \n').split()))
positive_num=[]
negative_num=[]
for x in numbers:
if x >0:
positive_num.append(x)
elif x <0:
negative_num.append(x)
print('positive numbers: ', positive_num)
print('negative numbers: ', negative_num)
print("nuetral number: 0")
numbers=list(映射(float,输入('enternumbers:\n').split())
正数值=[]
负数_num=[]
对于数字中的x:
如果x>0:
正数追加(x)
elif x如果x>0。。。如果x<0…
,则追加正数(x)
?您已经检查了数字的每个元素
使用x
进行比较。“它不起作用,因为数字是一个列表,而>0是一个变量”>0
不是一个变量,它是表达式的一部分,涉及
运算符和int
literal0
。它不起作用,因为numbers
是一个list
对象,0
是一个int
对象,不支持它们之间的
运算符。您应该在比较中使用x
而不是numbers
,然后将x
附加到相应的num列表中。
numbers = list(map(float, input( 'Enter numbers: \n').split()))
positive_num=[]
negative_num=[]
for x in numbers:
if x >0:
positive_num.append(x)
elif x <0:
negative_num.append(x)
print('positive numbers: ', positive_num)
print('negative numbers: ', negative_num)
print("nuetral number: 0")