简体   繁体   English

如何将带有字符串的文件中的数字转换为python列表中的整数

[英]How to convert numbers from file with strings to integer in a list in python

I'm trying to read a file which contains both names and numbers but I don't know how to convert the numbers to integers because they are on the same line with a string.我正在尝试读取一个包含名称和数字的文件,但我不知道如何将数字转换为整数,因为它们与字符串在同一行。 I also want to sort it with the numbers.我也想用数字对它进行排序。

This is like a scoreboard system and I want to print the top 5 player's scores and their names.这就像一个记分牌系统,我想打印前 5 名球员的分数和他们的名字。 Their scores are appended to a text file after they play a game which is read.在他们玩完游戏后,他们的分数会被附加到一个文本文件中。 The text file will have many more player's scores and names.文本文件将包含更多玩家的分数和姓名。

the file looks like this (we will call it data.txt):该文件如下所示(我们将其称为 data.txt):

Jack, 14
Amy, 2
Rock, 58
Jammy, 44

Once read, this is what the list looks like:阅读后,这是列表的样子:

['Jack, 14', 'Amy, 2', 'Rock, 58', 'Jammy, 44']

This is what I have done so far:这是我到目前为止所做的:

file = open("data.txt", "r")
Data = file.readlines()
Data = [line.rstrip('\n') for line in Data]

I have tried these:我试过这些:

Data.sort(key = lambda x: x[1])

Data = list(map(int, Data))

However, it shows an error because there is also a string on the same line which I don't want to be converted to an integer.但是,它显示一个错误,因为同一行上还有一个字符串,我不想将其转换为整数。

What I'm hoping to be output is:我希望输出的是:

Amy, 2
Jack, 14
Jammy, 44
Rock, 58

I just want to know how to sort by the numbers (scores) in ascending order with a newline.我只想知道如何使用换行符按升序对数字(分数)进行排序。

You could use the following key when sorting:排序时可以使用以下

data = ['Jack, 14', 'Amy, 2', 'Rock, 58', 'Jammy, 44']
data.sort(key=lambda s: int(s.split(',')[1].strip()))
print(data)

Output输出

['Amy, 2', 'Jack, 14', 'Jammy, 44', 'Rock, 58']

The idea is to split the string on ',' then remove any trailing whitespace from the second element and convert to an int.这个想法是在','上拆分字符串','然后从第二个元素中删除任何尾随空格并转换为 int。

It's probably best to store the names and scores in pairs rather than as a string最好成对存储名称和分数而不是字符串

from operator import itemgetter as ig
sorted_pairs = sorted(((pair[0], int(pair[1])) for pair in (line.split(', ') for line in file.readlines())), key = ig(0))

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

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