python - 如何遍历整数列表,并引用字典中的最大键(所有整数),使其小于当前值?
问题描述
我有一本带有正整数的字典keys
,这values
对我的问题无关紧要。
另外,我正在遍历 a list of integers
,并且我想引用字典中最大的键,它小于我在列表中迭代的当前整数(如果存在的话!)。
例如:
from collections import defaultdict
def Loep(obstacles):
my_dict = defaultdict(int)
output = []
for i in range(len(obstacles)):
if max(j for j in my_dict.keys() if j<= obstacles[i]):
temp = max(j for j in my_dict.keys() if j<= obstacles[i])
my_dict[obstacles[i]] = temp + 1
output.append(my_dict[obstacles[i]])
else:
my_dict[obstacles[i]] = 1
output.append(my_dict[obstacles[i]])
print(Loep([3,1,5,6,4,2]))
我收到上述错误-'if' statement
我相信这是因为我有太多参数max()
,有什么想法可以修改代码吗?
错误是:ValueError: max() arg is an empty sequence
我试过把它分开,但我做不到。
解决方案
像这样的东西:
from collections import defaultdict
def Loep(obstacles):
my_dict = defaultdict(int)
my_dict.update({
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
})
output = []
for obstacle in obstacles:
keys = [j for j in my_dict.keys() if j <= obstacle]
if keys:
# there is at least one qualifying key
key = max(keys)
my_dict[obstacle] = key + 1
output.append(my_dict[obstacle])
else:
my_dict[obstacle] = 1
output.append(my_dict[obstacle])
return output
print(Loep([3, 1, 5, 6, 4, 2]))
回应您关于在一行中执行此操作的评论.. 是的,您可以像这样浓缩它:
for obstacle in obstacles:
key = max([None]+[j for j in my_dict.keys() if j <= obstacle])
if key is not None:
# etc
..肯定还有其他方法可以做到这一点..使用过滤器..或其他方式..但是一天结束时,您不仅要获得最大值,还要使最大值低于特定值。除非您正在处理大量数据,或者需要极速……这是最简单的方法。
推荐阅读
- asp.net-core - 登录 Identity Server 4 - .Net Core 2.2
- c - 如何阅读这种格式
- sql - 如何增加保持字符串长度的最大值
- sql - 如果 X 但不是 Y,则 SQL 查询从表中返回所有内容
- c# - 我可以在收益返回方法中使用“使用”吗?
- node.js - 如何在 NodeJs、Express 和 JQuery 中生成 pdf 发票?
- php - 将函数参数传递给 ajax 数据返回未定义的索引错误
- php - laravel 警告和致命错误中要求打开失败
- python - __setitem__() 如何处理 4 个参数?
- java - 为 JLabel 设置背景图像后,如何在图像上显示文本?