Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Sorted()返回半排序的列表_Python_Arrays_Sorting - Fatal编程技术网

Python Sorted()返回半排序的列表

Python Sorted()返回半排序的列表,python,arrays,sorting,Python,Arrays,Sorting,我得到了一本类似这样的字典 sizeandstock = { '10.5': 132, '11.0': 66, '8.5': 80, '6.5': 10, '6.0': 31, '4.5': 36, '9.5': 133, '4.0': 48, '5.0': 12, '5.5': 32, '7.5': 9, '9.0': 110, '10.0': 131, '11.5': 54, '13.0': 11, '13.5': 7, '14.0': 11, '14.5

我得到了一本类似这样的字典

sizeandstock = {
 '10.5': 132,
 '11.0': 66,
 '8.5': 80,
 '6.5': 10,
 '6.0': 31,
 '4.5': 36,
 '9.5': 133,
 '4.0': 48,
 '5.0': 12,
 '5.5': 32,
 '7.5': 9,
 '9.0': 110,
 '10.0': 131,
 '11.5': 54,
 '13.0': 11,
 '13.5': 7,
 '14.0': 11,
 '14.5': 2,
 '16.0': 5,
 '17.0': 5,
 '7.0': 42,
 '12.0': 51,
 '8.0': 6,
 '12.5': 11}
正如您所看到的,大小没有排序,因此我编写了一个函数对其进行排序。我使用keys()获取字典中的键,keys()返回一个列表,然后迭代排序后的键,并将它们添加到一个新字典中,其中包含原始dict中的库存值

def sizesort (unsortedSizes):
    x = 0 
    sizedict = {}

    sortedsizes = sorted(unsortedSizes.keys())
    print(sortedsizes)
    for i in list(unsortedSizes):
        sizedict[sortedsizes[x]] = unsortedSizes[sortedsizes[x]]
        x = x+1
    return sizedict


print(sizesort(sizeandstock))
但是,它只返回排序后的列表

{'10.0': 131, '10.5': 132, '11.0': 66, '11.5': 54, '12.0': 51, '12.5': 11, '13.0': 11, '13.5': 7, '14.0': 11, '14.5': 2, '16.0': 5, '17.0': 5, '4.0': 48, '4.5': 36, '5.0': 12, '5.5': 32, '6.0': 31, '6.5': 10, '7.0': 42, '7.5': 9, '8.0': 6, '8.5': 80, '9.0': 110, '9.5': 133}

正如你所看到的,列表的前半部分是两位数,第二部分是一位数,我不知道为什么会这样,如果你知道原因或者知道如何得到结果,我正在寻求任何帮助,谢谢

您正在对字符串而不是数字进行排序。您需要强制转换为浮点数进行排序,然后返回到字符串进行索引:

def sizesort (unsortedSizes):
    x = 0 
    sizedict = {}

    sortedsizes = sorted([float(i) for i in unsortedSizes.keys())
    print(sortedsizes)
    for i in list(unsortedSizes):
        sizedict[str(sortedsizes[x])] = unsortedSizes[str(sortedsizes[x])]
        x = x+1
    return sizedict


print(sizesort(sizeandstock))

请看它是否正确排序。字符串
“4.0”
位于
“17.0”
之后,类似于
“Bob”
位于
“Alfred”