Python 从文件中读取字符串并将其拆分为值 [英] Python read in string from file and split it into values

查看:30
本文介绍了Python 从文件中读取字符串并将其拆分为值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式如下的文件:

995957,16833579995959,16777241995960,16829368995961,50431654

我想读取每一行,但将值拆分为适当的值.例如,第一行将被拆分为:

x = 995957y = 16833579

因为当你读入它时它是一个字符串,我想将它们转换为一个 int 并拆分它们,我到底要怎么做呢?任何帮助将不胜感激.

谢谢!

解决方案

类似这样的事情 - 将每一行读入字符串变量 a:

<预><代码>>>>a = "123,456">>>b = a.split(",")>>>乙['123', '456']>>>c = [int(e) for e in b]>>>C[123, 456]>>>x, y = c>>>X123>>>是456

现在您可以对指定的 xy 执行必要的操作,它们是整数.

I have a file in the format below:

995957,16833579
995959,16777241
995960,16829368
995961,50431654

I want to read in each line but split the values into the appropriate values. For example the first line would be split into:

x = 995957
y = 16833579

Since its a string when you read it in and I want to convert them to an int and split them, how exactly would I go about doing this? Any help would be appreciated.

Thanks!

解决方案

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

这篇关于Python 从文件中读取字符串并将其拆分为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆