简体   繁体   English

我正在尝试使用“a.sort([1])”用整数和浮点数对python中的列表进行排序,但它不起作用

[英]I am trying to sort a list in python with integers and a float using "a.sort([1])" and it is not working

I am trying to sort a list in python with integers and a float using "a.sort([1])" (I am sorting it from the second element of the list) but it keeps on saying "TypeError: must use keyword argument for key function".我正在尝试使用“a.sort([1])”(我从列表的第二个元素对它进行排序)用整数和浮点数对python中的列表进行排序,但它一直说“TypeError:必须使用关键字参数键功能”。 What should I do?我该怎么办? Also my list looks like this: ["bob","2","6","8","5.3333333333333"]我的列表也如下所示: ["bob","2","6","8","5.3333333333333"]

Paul's answer does a nice job of explaining how to use sort correctly.保罗的回答很好地解释了如何正确使用sort

I want to point out, however, that sorting strings of numbers is not the same as sorting numeric values (ints and floats etc.).但是,我想指出,对数字字符串进行排序与​​对数值(整数和浮点数等)进行排序不同。 Sorting by strings will use character collating sequence to determine the order, eg按字符串排序将使用字符整理顺序来确定顺序,例如

>>> l = ['100','1','2','99']
>>> sorted(l)
['1', '100', '2', '99']

but this is probably not what you want;但这可能不是您想要的; 100 is greater than 2 and so should appear further back in the list than 2. You can sort by numeric value, but retain strings for the list items using the key parameter to sort() : 100 大于 2,因此应该出现在列表中比 2 更靠后的位置。您可以按数值排序,但使用sort()key参数保留列表项的字符串:

>>> sorted(l, key=lambda x: float(x))
['1', '2', '99', '100']

Here the key is a lambda function that converts its argument to a float.这里的key是一个 lambda 函数,它将其参数转换为浮点数。 The sort() routine will use the converted value as the sort key, not the string value that is actually contained in the list. sort()例程将使用转换后的值作为排序键,而不是列表中实际包含的字符串值。

To sort from the second list item on, do this:要从第二个列表项开始排序,请执行以下操作:

>>> a = ["bob", "2", "6", "8", "5.3333333333333"]
>>> a[1:] = sorted(a[1:], key=lambda x: float(x))
>>> a
['bob', '2', '5.3333333333333', '6', '8']

try to do "a.sort()".尝试做“a.sort()”。 it will sort your list.它将对您的列表进行排序。 sort cant get 1 as argument.排序不能得到 1 作为参数。 read more here: http://www.tutorialspoint.com/python/list_sort.htm在此处阅读更多信息: http : //www.tutorialspoint.com/python/list_sort.htm

if you trying to sort every element except the first one try to do:如果您尝试对除第一个元素之外的每个元素进行排序,请尝试执行以下操作:

a[1:] = sorted(a[1:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM