如何确定给定数字是否在数字列表中?

发布于 2025-01-25 07:51:48 字数 302 浏览 2 评论 0原文

我想制作一个函数,以发现给定的数字是否在数字列表中。如何修复以下代码,以便它适用于由列表组成的列表?

lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9

def in_list_of_list(lst: list) -> bool:

    i = 0

    while i < len(lst) and lst[i] != num:
        i = i + 1
    return i < len(lst)
    
print(in_list_of_list(lst))

I want to make a function that finds out if a given number is in a list of lists of numbers. How do I fix the following code so that it works for a list consisting of lists?

lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9

def in_list_of_list(lst: list) -> bool:

    i = 0

    while i < len(lst) and lst[i] != num:
        i = i + 1
    return i < len(lst)
    
print(in_list_of_list(lst))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

第几種人 2025-02-01 07:51:48

您可以首先将列表弄平,然后轻松地在平面上检查:

lst = [[1, 2], [3, 4], [5, 6, 7]]

num = 9


def in_list_of_list(lst: list) -> bool:
    flat_list = [item for sublist in lst for item in sublist]
    return num in flat_list


print(in_list_of_list(lst))

You can flatten the list first, and then check easily in the flat one:

lst = [[1, 2], [3, 4], [5, 6, 7]]

num = 9


def in_list_of_list(lst: list) -> bool:
    flat_list = [item for sublist in lst for item in sublist]
    return num in flat_list


print(in_list_of_list(lst))
再可℃爱ぅ一点好了 2025-02-01 07:51:48

您询问该项目是否在列表的任何元素内部

def in_list_of_list(lst: list, item:object) -> bool:
    for sublist in lst:
        if item in sublist:
            return True
    return False

和快速测试

>>> lst = [[1, 2], [3, 4],[5, 6, 7]]
>>> in_list_of_list(lst, 9)
False
>>> in_list_of_list(lst, 7)
True
>>> 

you ask if the item is inside any of the elements of the list

def in_list_of_list(lst: list, item:object) -> bool:
    for sublist in lst:
        if item in sublist:
            return True
    return False

and a quick test

>>> lst = [[1, 2], [3, 4],[5, 6, 7]]
>>> in_list_of_list(lst, 9)
False
>>> in_list_of_list(lst, 7)
True
>>> 
对风讲故事 2025-02-01 07:51:48
lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9

def in_list_of_list(lst: list) -> bool:
    new_lst = []
    for a in lst:
        new_lst.extend(a) # add element from the inner list to new_list.
    return num in new_lst  # return True if the num inside the list else False.

print(in_list_of_list(lst))
lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9

def in_list_of_list(lst: list) -> bool:
    new_lst = []
    for a in lst:
        new_lst.extend(a) # add element from the inner list to new_list.
    return num in new_lst  # return True if the num inside the list else False.

print(in_list_of_list(lst))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文