繁体   English   中英

如何将浮点数从txt转换为Python列表作为字符串来回答问题?

[英]How to take floats from a txt to a Python list as strings to answer questions?

问题:

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

蟒蛇:

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

回答问题。 如何将浮点数从txt转换为字符串作为Python列表

码:

with open('haha.txt') as f:
    for line in f:
        words = line.split()
        print words
        my_list.append(words[1] + words[3])

我的测试代码无法产生预期的结果。 怎么了 我错过了, ...

['38.4397984061.1720742', '38.4398243061.1721378']

您是否尝试过非常明显的方法:

my_list.append(words[1] + "," + words[3])

顺便说一句,小小的评论:也许问这个问题作为对您在其他线程中已经接受的答案的评论而不是打开另一个问题是更合理的。

我不完全知道你想要什么,但我认为

my_list.append((words[1], words[3]))

将一个元组添加到my_list ,因此结果应为

[('38.43979840', '061.1720742'), ('38.43982430', '061.1721378')]

相反,您也可以这样做

my_list.append((float(words[1]), float(words[3])))

将代表数字的字符串转换为数字:

[(38.4397984, 61.1720742), (38.4398243, 61.1721378)]

暂无
暂无

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

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