作为值存储在可变长度字典中的列表 - 如何访问所有最后的列表项?
Lists stored as values in a dictionary of variable length - how to access all the last list items?
访问存储在字典中的所有最后列表项的最有效方法是什么?请注意,我正在寻找一种独立于字典中项目数量的解决方案。
例如,在这里我想检查一个数字是否高于列表中的最后一项。我想我找到了一个解决方案,但它看起来很复杂,我想知道是否有更好的方法。
input_num = 5
lst_dct = {
"lstA": [5, 12, 3, 4],
"lstB": [2, 3, 7, 11],
"lstC": [3, 8, 2, 20]
}
for key, value in lst_dct.items():
if input_num < value[-1]:
print("Input is **not** the highest.")
break
else:
print("Input is the highest.")
Returns正确:
Input is **not** the highest.
您已经非常接近最佳状态了。您可以将 items()
调用替换为 values()
以节省解包并稍微缩短代码,仅此而已。
if any(value[-1] >= input_num for value in lst_dct.values()):
print("Input is **not** the highest.")
else:
print("Input is the highest.")
访问存储在字典中的所有最后列表项的最有效方法是什么?请注意,我正在寻找一种独立于字典中项目数量的解决方案。
例如,在这里我想检查一个数字是否高于列表中的最后一项。我想我找到了一个解决方案,但它看起来很复杂,我想知道是否有更好的方法。
input_num = 5
lst_dct = {
"lstA": [5, 12, 3, 4],
"lstB": [2, 3, 7, 11],
"lstC": [3, 8, 2, 20]
}
for key, value in lst_dct.items():
if input_num < value[-1]:
print("Input is **not** the highest.")
break
else:
print("Input is the highest.")
Returns正确:
Input is **not** the highest.
您已经非常接近最佳状态了。您可以将 items()
调用替换为 values()
以节省解包并稍微缩短代码,仅此而已。
if any(value[-1] >= input_num for value in lst_dct.values()):
print("Input is **not** the highest.")
else:
print("Input is the highest.")