如何在Python的嵌套列表中查找项目?[已结束]

How to find an item in a nested list in Python? [closed]

提问人:Sherwin 提问时间:10/25/2023 更新时间:10/25/2023 访问量:51

问:


想改进这个问题吗?通过编辑这篇文章来更新问题,使其仅关注一个问题。

上个月关闭。

有一个嵌套列表 A:

A =  [[-1, 0, 1], [-2, 1, 9], [-3, 0, 7], [-4, 0, 5]]

如何检查 A 中是否有任何项目以 -1 ([-1, :, :]) 开头,如果是,它使用单个函数或方法而不是循环的索引是什么?

Python 函数 方法

评论

0赞 John Gordon 10/25/2023
解释为什么你不能使用循环。
0赞 Sherwin 10/25/2023
@JohnGordon 我使用了这个循环: counter = 0 for d in range(len(A)): if counter == 0: if len(A[d]) != 0: if A[d][0] == -1: index = d counter = 1 当 A 变大时,代码会变得非常慢。

答:

0赞 Prudhviraj 10/25/2023 #1

比方说,使用带有 a 和 函数的单行。list comprehensionnext()

index = next((i for i, sublist in enumerate(A) if sublist[0] == -1), None)
print(f"Index: {index}" if index is not None else "No items")

或者像这样的东西,在之后使用 if elseenumerate()

A = [[-1, 0, 1], [-2, 1, 9], [-3, 0, 7], [-4, 0, 5]]

matching_indices = [index for index, sublist in enumerate(A) if sublist[0] == -1]

if matching_indices:
    print("Found at indices:", matching_indices)
else:
    print("No items found.")

评论

1赞 Sherwin 10/25/2023
这也是 ChatGPT 给我的。我想要一些更简单的东西,使用“in”和index()也许?如果列表中有更多的巢穴怎么办?
0赞 Sherwin 10/25/2023
此代码@GRAYgoose124查找 -1 还是在任何地方查找 -1,还是仅查找以 -1 开头的子列表?
0赞 Prudhviraj 10/25/2023
@Sherwin你能给出 list() 中有更多嵌套的可重建场景
0赞 Prudhviraj 10/25/2023
@Sherwin我可以想到其中的嵌套列表,我可以建议使用与列表实例相同的逻辑检查输入的 recusrive 函数
1赞 ShadowRanger 10/25/2023
@Sherwin:除了 listcomps 和 genexprs 之外,您没有内置功能。 仅搜索特定值,而不搜索值的一部分。 是相似的。如果 listcomp/genexpr 不是一个选项,那么它就是或什么都不是。list.indexinnumpy
1赞 low_static 10/25/2023 #2

找到没有循环的所有索引是很困难的,除了像这样numpy的函数之外,我不知道还有什么方法可以做到这一点where()

import numpy as np

a = [[-1, 0, 1], [-2, 1, 9], [-3, 0, 7], [-4, 0, 5]]
search_value = -1

def find_indices(lst):
    np_array = np.array(lst)
    # Find indices where the first column is -1
    indices = np.where(np_array[:, 0] == search_value)[0]
    return indices

# Usage
indices= find_indices(a)
print(indices)  # Output: [0 3]

尽管 numpy 可能会在函数的引擎盖下使用循环,但这超出了我的知识范围where()