gpt4 book ai didi

python - 从文本文件中读取元组

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:09 29 4
gpt4 key购买 nike

我需要从 txt 中读取元组。我尝试使用 numpy(使用 genfromtxt)但它没有用(或者至少,我不知道如何)。这是我的文本:

(0,0) (0,0) (1,0) (2,3)
(1,0) (1,1) (1,1) (3,3)
(2,0) (1,2) (2,1) (4,4)
(3,0) (2,2) (3,1) (5,5)

我想逐一阅读本专栏并获取元组列表:尝试使用 numpy 我有这个:

import numpy as np
File = np.genfromtxt('file.txt',delimiter=' ', dtype= tuple)

但它返回的是字节类型元素的列表列表。

显然我可以更改数据在 txt 中的存储方式。我只需要从 txt 中获取元组列表(或列表列表)。

最佳答案

这是一种不使用任何库的简单方法:

tuples = []
for t in open('input.txt').read().split():
a, b = t.strip('()').split(',')
tuples.append((int(a), int(b)))

等价于列表推导式:

[tuple(int(i) for i in t.strip('()').split(',')) for t in open('input.txt').read().split()]


input.txt 是问题中提供的数据,这是输出:

[(0, 0), (0, 0), (1, 0), (2, 3), (1, 0), (1, 1), (1, 1), (3, 3), (2, 0), (1, 2), (2, 1), (4, 4), (3, 0), (2, 2), (3, 1), (5, 5)]

关于python - 从文本文件中读取元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48094176/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com