如何将浮点数从txt转换为字符串作为Python列表 [英] How to take floats from a txt to a Python list as strings

查看:167
本文介绍了如何将浮点数从txt转换为字符串作为Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手.我有以下问题.

I am very new at programming. I have the following problem.

我想从.txt文件中提取一些浮点数,然后将它们作为字符串添加到Python列表中,并且它们之间用逗号分隔,如下所示:

I want to take some floats from a .txt file, and add them to a Python list as strings, with a comma between them, like this:


.TXT:
194220.00   38.4397984  S   061.1720742 W   0.035
194315.00   38.4398243  S   061.1721378 W   0.036

Python:

myList = ('38.4397984,061.1720742','38.4398243,061.1721378')

有人知道该怎么做吗?谢谢!

Does anybody know how to do this? Thank you!

推荐答案

您需要执行三个关键步骤.您需要知道如何打开文件,您需要知道如何在打开文件的情况下通过行进行迭代,并且您需要知道如何到拆分列表.

There are three key pieces you'll need to do this. You'll need to know how to open files, you'll need to know how to iterate through the lines with the file open, and you'll need to know how to split the list.

一旦您了解了所有这些内容,就如同将所需的片段连接起来并将它们添加到列表中一样简单.

Once you know all these things, it's as simple as concatenating the pieces you want and adding them to your list.

my_list = []
with open('path/to/my/file.txt') as f:
    for line in f:
        words = line.split()
        my_list.append(words[1] + words[3])
print mylist

这篇关于如何将浮点数从txt转换为字符串作为Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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