简体   繁体   English

如何在Python中的每个字符串内基于浮点数对列表进行排序?

[英]How can I sort a list based on a float inside each string in Python?

I am trying to figure out how to sort a list based on a certain part of each string. 我试图弄清楚如何根据每个字符串的特定部分对列表进行排序。 How do I write the key? 我该如何编写密钥?

myKey(e)
  return e[-5,-2]

print(sorted(["A: (" + str(round(7.24856, 2)) + ")", "B: (" + str(round(5.8333, 2)) + ")"], key = myKey))

I want the output to look like this: ['B: (5.83)', 'A: (7.25)'] 我希望输出看起来像这样: ['B: (5.83)', 'A: (7.25)']

In my full code, there are more than two strings in the list, so I cannot just sort them reversed alphabetically. 在我的完整代码中,列表中有两个以上的字符串,因此我不能只按字母顺序对它们进行排序。

Thank you 谢谢

Your syntax for function myKey is wrong. 您的函数myKey语法错误。 Other than that, you have to slice out the number in the string with the correct index (from index of char '(' + 1 to the character before the last) and convert them to floating point number value so that the sorted function can work properly. 除此之外,您还必须在字符串中切出具有正确索引的数字(从char'('+ 1的索引到最后一个字符之前的字符),并将其转换为浮点数值,以便sorted函数可以工作正确地。

def myKey(e):
  return float(e[e.index('(')+1:-1])
print(sorted(["A: (" + str(round(7.24856, 2)) + ")", "B: (" + str(round(5.8333, 2)) + ")"], key = myKey))

You can use tuples sorted() to sort your data alongside with some list and string expressions to get the desired output: 您可以使用元组sorted()对数据以及一些列表和字符串表达式进行排序,以获得所需的输出:

input_list = ['A:(100.27)', 'B:(2.36)', 'C:(75.96)', 'D:(55.78)']
tuples_list = [(e.split(':(')[0], float(e.split(':(')[1][:-1])) for e in input_list]
sorted_tuples = sorted(tuples_list, key=lambda x: x[1])
result = [x[0] +':('+ str(x[1]) +')' for x in sorted_tuples]

print(input_list)
print(tuples_list)
print(sorted_tuples)
print(result)

Output: 输出:

['A:(100.27)', 'B:(2.36)', 'C:(75.96)', 'D:(55.78)']
[('A', 100.27), ('B', 2.36), ('C', 75.96), ('D', 55.78)]
[('B', 2.36), ('D', 55.78), ('C', 75.96), ('A', 100.27)]
['B:(2.36)', 'D:(55.78)', 'C:(75.96)', 'A:(100.27)']

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

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