简体   繁体   English

如果有负值,如何让 python 停止查找?

[英]How to make python stop looking if there is a negative value?

I have a dict:我有一个字典:

ff = {("Tom Brady",45678 ): [[456.0, 4050.0], [0.32, 5.6]]}

and

f = {("Tom Brady",45678 ): [[456.0, 4050.0, -1000.0], [0.32, 5.6, 4.56]]}

I have this code:我有这个代码:

def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int

for a in client_list[client][0]: 
    if a>0:
      return 2
    if a<0
      return 1

the problem with this code is that when there is no negative value, python gives me an error telling me it cannot be NoneType.这段代码的问题是,当没有负值时,python 给我一个错误,告诉我它不能是 NoneType。 I want the code to give me an answer if there is a negative, but instead it only gives me an error.如果有否定,我希望代码给我一个答案,但它只会给我一个错误。

You could make the list of lists (the value in your dictionaries) into one big list, and then use list comprehension to create a new list that only holds the negative numbers.您可以将列表列表(字典中的值)制作成一个大列表,然后使用列表推导创建一个仅包含负数的新列表。 If the length of this list comprehension result is bigger than 0, then you have negative numbers in any of the lists that is in the value of your dictionary.如果此列表理解结果的长度大于 0,则您的字典值中的任何列表中都有负数。

def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int:
    big_list = sum(client_list[client], [])
    negatives = [i for i in big_list if i < 0]
    if len(negatives) > 0:
        return True
    return False

(the sum is a little trick to create one list out of a list of lists). sum是从列表列表中创建一个列表的小技巧)。

As per comments;根据评论; if you only need to know if there was a negative number (and you will never need to know what number(s) those were), you could simplify:如果您只需要知道是否有负数(并且您永远不需要知道它们是什么数字),您可以简化:

def find_neg (client_list: dict[tuple[str, int], list[list[float]]], client: tuple[str, int]) -> int:
    big_list = sum(client_list[client], [])
    for i in big_list:
        if i < 0:
            return True
    return False

Your current logic is:您当前的逻辑是:

def help_find_neg(lst: list[float]):
    for element in lst: 
        if element > 0:
            return 2
        if element < 0:
            return 1
        # and if element == 0: go to the next element

If your lst consists only of zeros, the function will skip all of them (and return None ).如果您的lst仅包含零,则 function 将跳过所有这些(并返回None )。

This might be the reason behind your NoneType error.这可能是您的NoneType错误背后的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM