列出确定正值/负值以及它们是否大于/小于

2024-09-24 06:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我得到了下面的问题:给定一个整数列表,L,编写代码来确定列表中正整数的和是否 大于列表中负数之和的(绝对值)并打印适当的 留言。在

这是我为代码设计的,但它不起作用,它只是返回括号内的输入数字,例如input=-1,-2,4,5 output=(-1,-2,4,5)

def question(L):
   L = input()
   sumPositive = () #List where I will send the positive integers from "L" list
   sumNegative = () #List where I will send the negative integers from "L" list

   if x in L >= 0:
      append.x(sumPositive) #checks if the number is equal to or greater than 0, if so add it to          "sumPositive" list
  elif:
      append.x(sumNegative) #if not add it to "sumNegative" list

if sum(sumPositive) > abs(sum(sumNegative)):
   print "The sum of positive numbers is greater than the absolute value of negative numbers."
   elif: 
      sum(Positive) < abs(sum(sumNegative)):
         print "The sum of absolute value of negative numbers is greater than the sum of positive         numbers."
   else:
   print "They are equal."

有谁能告诉我我哪里出错了吗?或者我是不是做错了什么。谢谢!在


Tags: oftheto列表ifislistsum
3条回答

()创建空元组,而不是列表。append()是一种列表方法,例如foo.append(bar)。在

>>> def question(x):
...    s1=sum([i for i in x if i>0])
...    s2=sum([abs(i) for i in x if i<0])
...    if s1>s2:
...       print "The sum of positive numbers is greater than the absolute value of negative numbers."
...    elif s1<s2:
...       print "The sum of absolute value of negative numbers is greater than the sum of positive numbers."
...    else:
...       print "They are equal."
... 
>>> lst = [1,2,3,-1,-5,-7,3,-4,5,-6]
>>> question(lst)
The sum of absolute value of negative numbers is greater than the sum of positive numbers.
>>> lst=[-1,-2,3,2,3]
>>> question(lst)
The sum of positive numbers is greater than the absolute value of negative numbers.
>>> lst=[-2,-3,-3,3,2,3]
>>> question(lst)
They are equal.

更像Python的解决方案:

def question(lst):
    sum_pos = sum(x for x in lst if x >0)
    sum_neg = sum(abs(x) for x in lst if x<0)

    if sum_pos > sum_neg:
        print "The sum of positive numbers is greater than the absolute value of negative numbers."
    elif sum_pos < sum_neg:
        print "The sum of absolute value of negative numbers is greater than the sum of positive numbers."
    else:
        print "They are equal."

question([1,-1,-2,-2])

相关问题 更多 >