python - 当单个 if 语句为真时,如何获得假值?
问题描述
对不起,如果这是重复的问题。这是我第一次使用 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...
解决方案
对不起,我可以回答我自己的问题。
这里是。
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])
谢谢你们的帮助。
推荐阅读
- json - Azure 数据工厂中的分页
- reactjs - React.js gif 未加载
- angular - 将对象的某些属性映射为键值对
- python - 如何仅查找带有子锚点的元素?
- flask - 使用 Azure AD 登录的烧瓶舞示例
- stripe-payments - 无法在 Stripe Checkout 会话上设置元数据或客户端参考 ID
- java - 无法安装 Android Studio(IDE 无法创建目录 Mac)
- dialogflow-cx - Dialogflow CX - 如何清除参数
- python - 如何使用 Beautiful Soup 返回 YouTube 播放列表中所有 URL 的列表?
- python - 根据来自另一个 pyspark 数据帧的单词从 pyspark 数据帧中删除单词