【发布时间】:2021-07-12 22:24:13
【问题描述】:
我一直在尝试循环并排序包含字典的列表,其中包含值列表(SIDE_1 和 SIDE_2)。我想根据字典中每个列表的 0 索引进行排序。 EX:{'monday': [3, 2]},值 3 应该是排序标准。
我曾尝试使用 list sort() 方法,但我得到的最佳结果是两个 None 值(SIDE_1=None 然后 SIDE_2=None)。我也尝试过似乎更接近我的解决方案的 dict sorted() 方法,但是当我将 sorter() 函数作为键传递时,我总是得到 TypeError: string indices must be integers。
我已经通过打印测试了我的 sorter() 函数,并且我得到了我想要对我的列表进行排序的值,但是,当我尝试使用 sort() 或 sorted() 时,就会发生错误。
结果应该是:
SIDE_1: thursday, monday, wednesday, tuesday
SIDE_2: may, march, april, june
我的密码:
example = {'TOP': {'SIDE_1': [{'monday': [3, 2]}, {'tuesday': [1, 2]}, {'wednesday': [2, 1]}, {'thursday': [4, 0]}], 'SIDE_2': [{'march': [2, 1]}, {'april': [1, 2]}, {'may': [3, 3]}, {'june': [0, 3]}]}}
def sorter(obj):
for o in obj:
for h in o:
return o[h][0] # when I use print to test what value I am getting it works correctly. however, i do get None at the end of each loop.
for top in example:
for side in example[top]:
x = example[top][side]
print(sorted(x, key=sorter)) # if I just do print(sorter(x)) it returns the expected value(s)
结果:TypeError:字符串索引必须是整数。 --- 返回 o[h][0]
当我在 for 循环中打印(sorter(x)) 时,我得到: 3 1 2 4 没有 2 1 3 0 无
为什么我在每个循环结束时都得到 None?
【问题讨论】:
标签: python sorting dictionary nested