如何读取文本文件,然后将其转换为元组列表

时间:2019-04-13 14:03:14

标签: python-2.7 file tuples

我要转换的文本文件包含以下内容:

Alex
Gheith
40
John
Stewart
33

进入:

[('Alex','Gheith','40'),('John','Stewart','33')]

当前代码:

records =[]
f10 = open("PlayerRecords.txt","r")
for line in f10:
    line = line.strip()
    records.append(line)
t = ()
f10.close()
t = [(x,) for x in records]
print t

当前输出:

[('Alex','Gheith',40),('John','Stewart',33)]

1 个答案:

答案 0 :(得分:0)

尝试以下类似的方法。我已将str1作为多行字符串。

list1 = [line.strip() for line in str1.splitlines()]
l_iter = iter(list1)
mapped = zip(l_iter,l_iter,l_iter)
mapped = set(mapped)
print (mapped)