首页 > 解决方案 > 在 Python 中访问范围列表中的元素

问题描述

我创建了一个函数,它从用户那里获取一个数字 N,然后从用户那里请求一对数字 N 次。这些对作为范围附加到列表中。然后该函数返回范围列表。

在另一个函数中,我想找到这些范围内唯一元素的数量。所以这个列表被传递给这个函数。但是,我不确定如何从列表中的每个范围中获取数字。我想创建一个集合并将每个范围中的每个数字添加到该集合中。我创建了一个 for 循环来遍历列表中的每个元素。但是,当我创建一个空变量并将其设置为 x 元素处的列表时,我收到一个错误,显示为range object cannot be interpreted as an integer. 接下来,我尝试初始化一个空列表并将其设置为列表中的每个元素,但我收到了一个错误,显示为list indices must be integers or slices, not range.

这是我的部分代码的示例:

def get_input():
    
    num_events = int(input())
    events = []
    
    for i in range(0, num_events):
        si, ti = (input("Enter the start and end days of event #" + str(i + 1) + ": ").split())
        events.append(range(int(si), int(ti)))
    
    return events
def calculate(events):
    
    new_set = set()
    
    for l in events:
        
        check = events[l]
        new_set.add(check)
        
    unique_days = len(new_set)
        
    return unique_days

标签: pythonlistrange

解决方案


这是因为您正在尝试访问元素的一部分。让我解释 :

当你写for l in eventsl 是一个范围对象。您不能在范围对象上使用 [] 表示法。

最后,您需要独特天数的总和。

尝试这个 :

def get_input():

    num_events = int(input())
    events = []

    for i in range(0, num_events):
        si, ti = (input("Enter the start and end days of event #" +
                  str(i + 1) + ": ").split())
        events.append(range(int(si), int(ti)))

    return events


def calculate(events):

    new_set = set()
    unique_days = 0
    for check in events:

        new_set.add(check)

        unique_days += len(check)

    return unique_days

使用此代码,输出将是例如:

events = get_input()
# num_events = 2
# date for day 1 : 1 and 3
# date for event 2 : 4 and 5
ud = calculate(events)
print(ud) # print (3-1) + (5-4) = 2 + 1 = 3

推荐阅读