[英]Check if all elements in nested list are positive or negative in python
I am trying to use a list comprehension to find the nested list whose elements are all positive, but I am not sure how to phrase the conditional to check all the values in the nested list for the list comprehension.我正在尝试使用列表推导来查找其元素均为正数的嵌套列表,但我不确定如何用条件语句检查嵌套列表中的所有值以进行列表推导。
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
I think this is the statement I am trying to turn into code: "if all n > 0 for n in i, return index i"我认为这是我试图将其转换为代码的语句:“如果 i 中的 n 的所有 n > 0,则返回索引 i”
edit: Output would be to return the index of the corresponding row of all positive numbers编辑: Output 将返回所有正数对应行的索引
You are close.你很亲密。 Imagine how you would do this in a loop:
想象一下您将如何循环执行此操作:
for index, row in enumerate(records):
if all(col > 0 for col in row):
print(index)
The if
condition with all
returns True if all elements are positive only.如果所有元素都是正数,
if
条件all
返回 True。 Now put this into list comprension form:现在把它变成列表压缩形式:
answer = [
index
for index, row in enumerate(records)
if all(col > 0 for col in row)
]
# [2]
List comprehensions are optimized versions of for loops specifically made for creating lists.列表推导是专门用于创建列表的 for 循环的优化版本。 There is usually a one-to-one translation between a loop generating a list, and a list comprehension.
在生成列表的循环和列表推导之间通常存在一对一的转换。 My advice when you are stuck on list comp syntax is to take a step back and visualize what this looks like as a simple for loop.
当您陷入列表组合语法时,我的建议是退后一步,将这看起来像一个简单的 for 循环。 Here are two important rules of optimization (as told to me by my mentor in university):
以下是优化的两个重要规则(正如我的大学导师告诉我的):
You can use all
to check whether all elements satisfy a given condition, eg您可以使用
all
检查所有元素是否满足给定条件,例如
answer = [all(n > 0 for n in lst) for lst in records]
You may use the all
built-in method that您可以使用
all
内置方法
Return True if all elements of the iterable are true (or if the iterable is empty)
如果可迭代对象的所有元素都为真(或可迭代对象为空),则返回 True
for all negative对于所有负面的
answer = [all(n < 0 for n in i) for i in records] # [False, False, False, False, False]
for all positive对于所有积极的
answer = [all(n > 0 for n in i) for i in records] # [False, False, True, False, False]
To get indexes of all-positive rows , combine with enumerate
要获取所有正数行的索引,请结合
enumerate
answer = [idx for idx,row in enumerate(records) if all(n > 0 for n in row)] # [2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.