Python 如何将文件中的信息转换为元组

Python 如何将文件中的信息转换为元组,python,Python,我必须创建一个文件:planets.txt,其中包含关于行星的信息。该文件如下所示: Planet1 100 200 planet2 200 300 planet3 400 250 >>> [tuple(map(int, item)) for item in res] [(100, 200), (200, 300), (400, 250)] 我必须用python编写一个函数,返回一个包含以下信息元组的列表: [(100,200),(200,300),(400,250)]

我必须创建一个文件:planets.txt,其中包含关于行星的信息。该文件如下所示:

Planet1 100 200

planet2 200 300

planet3 400 250
>>> [tuple(map(int, item)) for item in res]
[(100, 200), (200, 300), (400, 250)]
我必须用python编写一个函数,返回一个包含以下信息元组的列表:

[(100,200),(200,300),(400,250)]
问题是我不知道如何编写这个函数。有人能帮我吗?
非常感谢

大概是这样的吧

ret = []
lines = open('file.txt').readlines()
for line in lines:
    name, first, second = line.split(' ')
    ret.append((int(first), int(second)))

也许是这样的

ret = []
lines = open('file.txt').readlines()
for line in lines:
    name, first, second = line.split(' ')
    ret.append((int(first), int(second)))

您需要拆分文件的每一行,并将每个结果列表的第二项和第三项的元组附加到
res
列表中,如下所示:

res = []

with open('planets.txt', 'r') as f:
    for line in f:
        if line.split():  # I add this because from your input, seems that your file contains some blank lines!
            res.append(tuple(line.split()[1:]))
输出:

>>> res
[('100', '200'), ('200', '300'), ('400', '250')]
可以将每个元组的项转换为如下所示的整数:

Planet1 100 200

planet2 200 300

planet3 400 250
>>> [tuple(map(int, item)) for item in res]
[(100, 200), (200, 300), (400, 250)]

您需要拆分文件的每一行,并将每个结果列表的第二项和第三项的元组附加到
res
列表中,如下所示:

res = []

with open('planets.txt', 'r') as f:
    for line in f:
        if line.split():  # I add this because from your input, seems that your file contains some blank lines!
            res.append(tuple(line.split()[1:]))
输出:

>>> res
[('100', '200'), ('200', '300'), ('400', '250')]
可以将每个元组的项转换为如下所示的整数:

Planet1 100 200

planet2 200 300

planet3 400 250
>>> [tuple(map(int, item)) for item in res]
[(100, 200), (200, 300), (400, 250)]

如果您正在寻找紧凑的代码

f = open('your_file_path').readlines()
print [tuple(map(int,a.split()[1:])) for a in f if a != '\n']
输出:

[(100, 200), (200, 300), (400, 250)]

如果您正在寻找紧凑的代码

f = open('your_file_path').readlines()
print [tuple(map(int,a.split()[1:])) for a in f if a != '\n']
输出:

[(100, 200), (200, 300), (400, 250)]

planets.txt
中“真实”行之间的换行符是否真的存在?开始阅读并练习示例-它会给你一些想法。更多资源-。你读过/练习过你收到的教学材料吗?
planets.txt
中“真实”行之间的换行符实际存在吗?开始阅读并练习这些示例-它会给你一些想法。更多资源-。你读过/练习过你收到的教学材料吗?为什么不把
关键字一起使用呢?好问题。我正在使它紧凑<使用编码>是一个更好的选择。我想知道由于引用计数为零,文件对象会发生什么情况。检查以下答案:为什么不将
关键字一起使用?好问题。我正在使它紧凑<使用编码>是一个更好的选择。我想知道由于引用计数为零,文件对象会发生什么情况。检查此答案:无需调用
.readlines()
。只需对f:中的行循环
,并避免在解析时一次只需要一行时无缘无故地保留内存中的所有行(注意:我还是投了赞成票,因为你是唯一正确使用
的答案)@ShadowRanger谢谢。我知道
readlines()
不是必需的。我只是喜欢显式的东西,但无论如何我都会删除它!无需调用
.readlines()
。只需对f:
中的行循环
,并避免在解析时一次只需要一行时无缘无故地保留内存中的所有行(注意:我还是投了赞成票,因为你是唯一正确使用
的答案)@ShadowRanger谢谢。我知道
readlines()
不是必需的。我只是喜欢显式的东西,但无论如何我都会删除它!