【问题标题】:How can I get false values when single if statement is true?当单个 if 语句为真时,如何获得假值?
【发布时间】:2019-09-23 17:19:35
【问题描述】:

对不起,如果这是重复的问题。这是我第一次使用 StackOverflow。我也是 Python 的初学者。

所以,这里是代码。

def count_positives_sum_negatives(arr):
    #your code here
  array = [0, 0] #array[0] for sum of positives.  array[1] for sum of negatives.

  for x in arr:
    if x > 0:
      array[0] = array[0] + x
      print(array)



count_positives_sum_negatives([1,2,3,4,-5])

基本上,我想创建一个包含正数总和和负数总和的数组。对于给定的数组,它应该返回[10, -5]. 现在,我想学习和理解一些东西,当单个 if 语句为 true 时,我怎样才能得到 false 值?我正在考虑使用双 if 语句或 while 循环,但是单 if 语句可以做到这一点吗?
当 if 语句条件为真时,数组变为 [10, 0] 所以现在我有了正数的总和。我应该如何得到否定的总和-5,这是单个 if 语句的假值?

问题 2:为什么我得到一个重复的值?我没有使用return 来停止循环,所以我对这段代码感到困惑。

for x in arr:
    while x > 0:
       print(x) # Print 1 again and again...

【问题讨论】:

  • 您的代码似乎没有考虑负数的情况。
  • 您只是在寻找else吗?
  • while x > 0: 是一个无限循环,如果循环内没有任何变化 x。这是一个微不足道的重复,可能应该简单地从这篇文章中删除。一次只问一个问题。
  • 对于您的第一个问题.. 答案是使用 else.... 在此处提问之前,我建议您学习任何在线教程的基础知识
  • 是的,我可以使用条件y < 0 执行另一个 if 语句并使用它来获取负值。但我想知道是否有可能同时获得真值和假值?不仅仅是真实的价值观

标签: python arrays for-loop if-statement


【解决方案1】:

使用以下语法:

if x>0:
   ... 
else:
   ...

附加问题:应该有if,而不是while。

【讨论】:

    【解决方案2】:

    一种方法如下,完全不使用 if 条件:

    def count_positives_sum_negatives(arr):
        #your code here
      array = [0, 0] #array[0] for sum of positives.  array[1] for sum of negatives.
    
      for x in arr:
         array[int(x<0)] += x
      print(array)
    
    
    
    count_positives_sum_negatives([1,2,3,4,-5])
    

    【讨论】:

      【解决方案3】:

      抱歉,我本可以回答我自己的问题。

      在这里。

      def count_positives_sum_negatives(arr):
          #your code here
        array = [0, 0] #array[0] for sum of positives.  array[1] for sum of negatives.
      
        for x in arr:
          if x > 0:
            array[0] = array[0] + x
          else:
            array[1] = array[1] + x
          print(array)
      
      
      
      count_positives_sum_negatives([1,2,3,4,-5])
      

      感谢大家的帮助。

      【讨论】:

        【解决方案4】:

        你可以试试这样的:

        for element in array:
            if element > 0:
              aggregation[0] += element
            else:
              aggregation[1] += element
        

        如果你想要精简版:

        for element in array:
            aggregation[0 if element>0 else 1] += element
        

        【讨论】:

        • 第二种情况下应该有索引1
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        • 2021-04-11
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        • 2014-09-07
        相关资源
        最近更新 更多