检查列表是否包含特定范围内的元素

时间:2021-02-23 18:49:35

标签: python list count range element

通过搜索类似的问题,我发现了如何使用 in 来检查列表是否包含特定元素。但是我无法找到如何检查和计算列表的特定范围内是否存在元素。

示例:

Inventory = [1, 2, 3, 5, 1, 2, 3, 3, 5, 0, 1, 5, 3, 6, 1, 0, 2, 4, 2, 8]

列表中有 20 个元素和 2 个 0 实例。我想计算每 5 个元素中包含多少个零实例,其输出类似于:

Elements 1–5 contain 0 zeroes.
Elements 6-10 contain 1 zeroes.
Elements 11-15 contain 0 zeroes.
Elements 16-20 contain 1 zeroes.

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

Python 列表的索引从零开始(从零开始),因此输出中提到的索引将是人为的。

您可以使用索引范围中的一个步骤和这些索引中长度为 5 的下标,以 5 个块为单位遍历您的列表:

Inventory = [1, 2, 3, 5, 1, 2, 3, 3, 5, 0, 1, 5, 3, 6, 1, 0, 2, 4, 2, 8]
counts    = [(i,Inventory[i:i+5].count(0)) for i in range(0,len(Inventory),5)]

for i,count in counts:
    print(f"Elements {i+1}–{i+5} contain {count} zeroes.")

Elements 1–5 contain 0 zeroes.
Elements 6–10 contain 1 zeroes.
Elements 11–15 contain 0 zeroes.
Elements 16–20 contain 1 zeroes.

答案 1 :(得分:0)

您可以将列表分割成您想要的范围并在那里搜索元素,如下所示:

if element in Inventory[start:end]:
    # Do something