英文:
read values in a file and convert them according to their type in python
问题
我有以下文件:
10 10 11 10530 18 100 0 Open ;
11 11 12 5280 14 100 0 Open ;
12 12 13 5280 10 100 0 Open ;
21 21 22 5280 10 100 0 Open ;
我按照以下方式读取文件:
with open(file) as f:
values = line.rstrip().split()
这是第一行的结果:
values
Out: ['10', '10', '11', '10530', '18', '100', '0', 'Open']
我想将其中一些转换为整数、浮点数或保持为字符串。
最简单的方法可能是:
values[0] = int(values[0])
values[1] = int(values[1])
values[2] = int(values[2])
values[3] = float(values[3])
values[4] = float(values[4])
values[5] = float(values[5])
values[6] = float(values[6])
values[7] = values[7]
你有没有其他更紧凑或更智能的方法来实现这个目标?
例如,我可以在文件中将要转换为浮点数的值写成浮点数,通过添加一个小数点,例如,将2写成2.0。然而,我再次陷入了转换的问题。
感谢任何形式的帮助。
英文:
I have the following file:
10 10 11 10530 18 100 0 Open ;
11 11 12 5280 14 100 0 Open ;
12 12 13 5280 10 100 0 Open ;
21 21 22 5280 10 100 0 Open ;
I read the file as follow:
with open(file) as f:
values = line.rstrip().split()
this is the outcome for the first line:
values
Out [2]: ['10', '10', '11', '10530', '18', '100', '0', 'Open']
I would like to convert some of them to integer, float or keep them as string.
The easiest way could be the following:
values[0] = int(values[0])
values[1] = int(values[1])
values[2] = int(values[2])
values[3] = float(values[3])
values[4] = float(values[4])
values[5] = float(values[5])
values[6] = float(values[6])
values[7] = values[7]
Do you have in mind other more compact or smarter way to do that?
I could for example write the values that I want to convert to float as float in the file by adding a dot. For example, 2 as 2.0.
However, I am stuck again with the conversion.
Thanks for any kind of help
答案1
得分: 1
我认为你正在寻找的可能是这样的代码:
values[0:2] = [int(values[i]) for i in range(3)]
values[3:6] = [float(values[i]) for i in range(3, 7)]
这样做可以避免重复编写代码行,尽管这不是最佳实践。
如果你想学习更好的文件解析方法,我建议你学习如何使用 pandas。
英文:
I think what you're looking for might be something like this:
values[0:2] = [int(values[i]) for i in range(3)]
values[3:6] = [float(values[i]) for i in range(3, 7)]
This should save you duplicating your code lines although it isn't the best practice to do it.
If you're into learning a better way to do this kind of file parsing I would recommend you to learn how to use pandas
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论