【问题标题】:Checking elements in a list of integers for positive or negative values检查整数列表中的元素的正值或负值
【发布时间】:2021-10-18 17:39:20
【问题描述】:

我有一个预先创建的整数列表,如果值符合条件,我想遍历并附加“正”或“负”。但是它在我的 if 语句的第一行抛出 "TypeError: '>' not supported between 'str' and 'int' 。我之前在获取用户输入时看到过这个错误并且必须将输入转换为 int,但我的列表已经是一个整数,所以我对需要修复的内容感到困惑。它在 if lst[i] > 0:

上抛出错误
lst = [-2, 1, -2, 7, -8, -5, 0, 5, 10, -6, 7]

for i in lst:
    if lst[i] > 0:
        lst.append("positive")
    elif lst[i] < 0:
        lst.append("negative")
    else:
        lst.append("zero")

【问题讨论】:

  • 使用 i 代替 lst[i]docs.python.org/3/tutorial/datastructures.html。并将文本附加到另一个列表。
  • 您在遍历列表时将其添加到列表中,因此有时会将整数(最后一个)与第一个字符串进行比较。预期的输出是什么?
  • 为什么要将结果附加到同一个列表中?

标签: python list


【解决方案1】:

解决方案

[('negative', 'zero', 'positive')[((n > 0) - (n < 0)) + 1] for n in lst]

说明

在线代码使用列表推导来创建列表。

  1. ('negative', 'zero', 'positive') 是将要从中获取字符串的字符串元组。

  2. [((n &gt; 0) - (n &lt; 0)) + 1] 获取字符串。让我们分解一下:

    子表达式 (se) (n &gt; 0) - (n &lt; 0) 给出 n 的符号(如果 n 0 则为 +1) 注意:Python 没有sign 函数。

    # Keep in mind that True = 1 and False = 0
    if n < 0  'se' evaluates to False - True  => 0 - 1 => -1
    if n > 0  'se' evaluates to True  - False => 1 - 0 =>  1
    if n == 0 'se' evaluates to False - False => 0 - 0 =>  0
    
  3. 然后我们加 1 得到:如果 n 0,则为 2。

  4. 最后,我们使用这个整数作为字符串元组中的索引。

等效代码为:

strings=('negative', 'zero', 'positive')

def sign(n):
    """Returns the sign of n: -1 if n < 0, 0 if n == 0, +1 if n > 0"""
    return (n > 0) - (n < 0)
    
rtn = [] # will get the result
for n in lst:
    index = sign(n) + 1
    string = strings[index]
    rtn.append(string)

【讨论】:

    【解决方案2】:

    你应该这样做:

    lst = ["positive" if el > 0 else "negative" if el < 0 else "zero" for el in [-2, 1, -2, 7, -8, -5, 0, 5, 10, -6, 7]]
    

    以更快、更简洁的方式创建您需要的内容。

    返回:

    ['negative', 'positive', 'negative', 'positive', 'negative', 'negative', 'zero', 'positive', 'positive', 'negative', 'positive'] 
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2020-03-19
      • 2014-12-07
      • 2016-04-23
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多