簡體   English   中英

當單個 if 語句為真時,如何獲得假值?

[英]How can I get false values when single if statement is true?

對不起,如果這是重復的問題。 這是我第一次使用 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語句為真時,我怎樣才能得到假值? 我正在考慮雙 if 語句或 while 循環,但這可能與單 if 語句嗎?
當 if 語句條件為真時,數組變為 [10, 0] 所以現在我有了正數的總和。 我應該如何使用單個 if 語句獲得否定值的總和-5

問題2:為什么我得到一個重復的值? 我沒有使用return來停止循環,所以我對這段代碼感到困惑。

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

使用以下語法:

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

附加問題:應該有if ,而不是while

你可以嘗試這樣的事情:

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

一種方法如下,根本不使用 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])

對不起,我可以回答我自己的問題。

這里是。

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])

謝謝你們的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM