python-3.x - 检查元素是否存在于列表列表中的第 N 个位置

标签 python-3.x list

考虑一下这个列表:

ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 4, 3, 21], 
            [45, 65, 8, 8, 9]]

我需要能够查找列表列表的任何第三个元素中是否存在 4。因此,在这个示例中,我看到它确实存在于第二个列表 [4, 3, 4, 3, 21] 的位置 1 和 3 上,因此它将返回 true。

我可以做到这一点:

elem_to_find = 4
res1 = any(elem_to_find in sublist for sublist in ini_list)

但是通过这样做,我将搜索所有列表元素列表,而不仅仅是每个列表的第三个元素。什么是正确的方法?

最佳答案

你可以这样做:

res1 = any(elem_to_find == sublist[2] for sublist in ini_list if len(sublist) > 2)

这会将 elem_to_findsublist[2] 进行比较,而不仅仅是 sublist,即第三个元素而不是整个列表。它还确保子列表的长度大于 2(否则第三个元素将不存在)。

下面是包含 2 个示例的完整代码:

ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 4, 3, 21], 
            [45, 65, 8, 8, 9]]

elem_to_find = 4
res1 = any(elem_to_find == sublist[2] for sublist in ini_list if len(sublist) > 2)

print(res1)
# Prints True

ini_list = [[1, 2, 5, 10, 7], 
            [4, 3, 3, 3, 21],  # No longer has 4 in 3rd position
            [45, 65, 8, 8, 9]]

res1 = any(elem_to_find == sublist[2] for sublist in ini_list if len(sublist) > 2)
print(res1)
# Prints False

关于python-3.x - 检查元素是否存在于列表列表中的第 N 个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66286285/

相关文章:

c# - 在 C# 的列表中循环遍历列表

python - 为什么我收到错误 : "NameError: global name ' pupiluserinputbox' is not defined"

python-3.x - PyQt : How do you clear focus on startup?

python - 如何在不更改类变量的情况下编辑函数的返回值

python - 为什么python list没有len()方法

python - 按范围排列列表

Python - 如何编写一个循环以根据另一个列表的元素python为列表中的每个df添加一列

python - 检测图像中的文本位置并在 Python 中裁剪它

python - 问题,在 python 3.7 中构建开关盒

python - 检查列表字典中是否有值的最佳方法?