检查 python 中嵌套列表中的所有元素是否为正数或负数

Check if all elements in nested list are positive or negative in python

我正在尝试使用列表理解来查找其元素全部为正的嵌套列表,但我不确定如何用条件语句来检查嵌套列表中的所有值以进行列表理解。

records = [[-167.57, 4.0, 61.875, -100.425],
 [-1.75, 3.75, 4.0],
 [7612.875, 10100.0, 74.25, 1.75, 61.875],
 [-2333.37, -5404.547500000001, -5178.645833333333, 97.0, 167.57],
 [-96.99999999999997, -5277.999999999999, -4998.5, 74.25, 3.75]]

answer = [i for i in records if (n < 0 for n in i)]
answer

我想这就是我要转换成代码的语句:"if all n > 0 for n in i, return index i"

编辑:输出将是return所有正数对应行的索引

您可以使用all来检查是否所有元素都满足给定的条件,例如

answer = [all(n > 0 for n in lst) for lst in records]

您可以使用 all 内置方法

Return True if all elements of the iterable are true (or if the iterable is empty)

  • 全部否定

    answer = [all(n < 0 for n in i) for i in records] # [False, False, False, False, False]
    
  • 所有正数

    answer = [all(n > 0 for n in i) for i in records] # [False, False, True, False, False]
    

要获取 全正行 的索引,请结合 enumerate

answer = [idx for idx,row in enumerate(records) if all(n > 0 for n in row)] # [2]

你很接近。想象一下您将如何在循环中执行此操作:

for index, row in enumerate(records):
    if all(col > 0 for col in row): 
        print(index)

if 条件 all returns 只有所有元素都为正时才为真。现在将其放入列表压缩形式:

answer = [
    index 
    for index, row in enumerate(records) 
    if all(col > 0 for col in row)
]
# [2]

列表理解是 for 循环的优化版本,专门用于创建列表。在生成列表的循环和列表理解之间通常存在一对一的转换。当你被 list comp 语法困住时,我的建议是退后一步,将这看起来像一个简单的 for 循环。这里有两个重要的优化规则(我的大学导师告诉我的):

  1. 不优化
  2. 先不要优化