我需要从txt中读取元组。我尝试使用numpy(使用genfromtxt),但它没有工作(或者至少,我不知道如何)。 这是我的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)
我想逐一阅读这些列并获取元组列表: 试着用numpy我有这个:
import numpy as np
File = np.genfromtxt('file.txt',delimiter=' ', dtype= tuple)
但它返回一个包含字节类型元素的列表列表。
显然我可以改变数据存储在txt中的方式。我只需要从txt获取元组列表(或列表列表)。
答案 0 :(得分:4)
这是一种不使用任何库的简单方法:
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)]
答案 1 :(得分:2)
你可以试试这个,虽然它不使用numpy
库:
from ast import literal_eval as createTuple
tupleList = []
with open("test.txt","r") as infile:
for line in infile:
line = line.split()
for l in line:
tupleList.append(createTuple(l))
print(tupleList)
输入文件的格式:
(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)
输出(元组列表):
[(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)]
答案 2 :(得分:1)
你也可以在这里尝试正则表达式:
import re
pattern='\((\d+,\d)\)'
with open('demo.txt','r') as f:
for line in f:
data=re.findall(pattern,line)
data_1=[]
for item in data:
data_1.append(tuple(map(lambda x:int(x),item.split(','))))
if data_1:
print(data_1)
输出:
[(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)]
甚至更好:
import re
pattern='\((\d+,\d)\)'
with open('demo.txt','r') as f:
for line in f:
data=re.findall(pattern,line)
data_1=[tuple(map(lambda x:int(x),item.split(','))) for item in data]
if data_1:
print(data_1)