python - 在 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
解决方案
这是因为您正在尝试访问元素的一部分。让我解释 :
当你写for l in events
l 是一个范围对象。您不能在范围对象上使用 [] 表示法。
最后,您需要独特天数的总和。
尝试这个 :
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
推荐阅读
- c++ - 从特征匹配/单应性中过滤掉误报——OpenCV
- html - 如何在 readthedown 中通过 rmarkdown 创建的 html 报告中减少/删除右侧的灰色条?
- python - 如何在 PyQt 界面中显示剪贴板中的 RTF 内容?
- python - 使用 keras 和 tensorflow 调整大小会产生不同的结果
- c# - 物理。模拟每一帧
- python - 我该如何解决这个问题(可能是错误语法)
- javascript - 为什么我的表格列数超过8时ajax会返回“Page not found”错误
- javascript - Axios 在调用之前取消令牌取消请求
- node.js - 车把活动 TAB
- python - Eve:如何使用不同的端点访问具有不同过滤器的同一个集合