[英]I have a txt file with a list of letters and numbers, and I need to sort it based on the numbers, how do I go about doing this?
What I have so far is a program that reads a text file, and puts it into a list. 到目前为止,我有一个程序可以读取文本文件,并将其放入列表中。 The txt file looks like:
txt文件如下所示:
asdf:15.3 eazzz:31.12 qw:1.65 ...
I am kind of new to Python so I'm still trying to figure out how to do this properly. 我是Python的新手,因此我仍在尝试找出如何正确执行此操作。 I know this will separate the numbers from the letters, but I don't know where to go from here.
我知道这会将数字和字母分开,但是我不知道从这里去哪里。
def get_num(str):
items = str.split(':')
return float(items[1])
The desired output will have the numbers sorted out in descending order with their respective letters. 所需的输出将具有按降序排列的数字及其相应的字母。 I know this can probably be done with "sort" but if possible I'd also like to see it done with for-loops.
我知道可以使用“ sort”完成此操作,但如果可能的话,我也希望使用for循环完成此操作。
Don't use str as the input name. 不要使用str作为输入名称。 To sort a list containing tuples
(name, value)
just do the following: 要对包含元组
(name, value)
的列表进行排序(name, value)
只需执行以下操作:
sorted(list_name, key = lambda x : x[1], reverse = True)
key = lambda x : x[1]
indicates that you want to sort the list by value
while reverse = True
indicates that you want the sort to be in descending order. key = lambda x : x[1]
表示要按value
对列表进行排序,而reverse = True
表示要按降序对列表进行排序。
data = '''asdf:15.3
eazzz:31.12
qw:1.65
adasf:7.3'''
# convert string to list
lst = data.split('\n')
#sort list of data by two things. first the string part second number part
print '\n'.join(sorted(lst, key=lambda item:(item.split(':')[0],float(item.split(':')[1])), reverse = True))
output: 输出:
qw:1.65
eazzz:31.12
asdf:15.3
adasf:7.3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.