以下是我在文本文件中的内容:
1712 Albert
1703 Benny
1799 Henry
1735 Jessica
1722 Lucas
1701 Luke
1757 William
1777 Jenny
1783 Lucia
1764 Venus
1718 Felicitas
这是我为阅读文件所做的工作,但我不知道如何将它们放入元组列表中
def readRecords(filepath):
file = open('Students1.txt', 'r')
filecontent = file.readlines()
file.close()
return filecontent
这是输出应该是什么:
答案 0 :(得分:1)
def readRecords(filepath):
result = []
with open('Students1.txt', 'r') as f: # close the file outside of `with`
for line in f: # Iterate over lines
num, name = line.split() # split line into two part
num = int(num) # convert number part to `int`
result.append((num, name))
return result
注意:除非您需要一次使用整行,否则请勿使用readlines()
。你一次只需要一条线;迭代文件就足够了。
答案 1 :(得分:1)
只需打开文件,然后拆分这些行,我意识到您需要的结果就像(int, string)
,因此您可以使用map
执行此操作,然后返回元组:
with open('out.csv') as f:
print([tuple(map(lambda x: int (x) if x.isdigit() else x,i.split())) for i in f])
输出:
[(1712, 'Albert'), (1703, 'Benny'), (1799, 'Henry'), (1735, 'Jessica'), (1722, 'Lucas'), (1701, 'Luke'), (1757, 'William'), (1777, 'Jenny'), (1783, 'Lucia'), (1764, 'Venus'), (1718, 'Felicitas')]
答案 2 :(得分:1)
def readRecords(filepath):
rst = []
with open(filepath) as f:
data = f.read().splitlines()
rst = [(int(x.split(' ')[0]), x.split(' ')[1]) for x in data]
return rst
答案 3 :(得分:0)
您必须遍历刚刚阅读的文件中的行。这是你能做的:
def readRecords(filepath):
file = open(filepath, 'r') # You should use the filepath variable you've given
filecontent = file.readlines()
file.close()
my_tuples = []
for line in filecontent: # For each line in the file...
line = line.strip() # Remove the newline character which you likely don't want
my_tuples.append(int((line.split(' ')[0]), line.split(' ')[1])) # Create a tuple of the two words separated by a space
return my_tuples
print(readRecords('Students1.txt'))
答案 4 :(得分:0)
根据您从文件中读取的行,如下所示:
def process_lines(lines):
result = []
for line in lines:
parts = line.strip().split(" ")
result.append(tuple(int(parts[0]), parts[1]))
return result
这里可以进行列表理解,但这需要很多紧张。在简化代码时使用listcomps,当它们变得更复杂时避免使用它们。 (或当他们要求你计算两次相同的值时)
答案 5 :(得分:0)
如果你想要一个很好的短两行方法:
lines = [x.rstrip() for x in open('students.txt')]
output = [tuple(pair.split(' ')) for pair in lines]
print(output)
# [('1712', 'Albert'), ('1703', 'Benny'), ('1799', 'Henry')...
答案 6 :(得分:-2)
Location = ["1712","1703","1799",...]
Name = ["Albert","Benny","Henry",...]
使用zip功能:
z = zip(Location, Name)
print z
输出:
[("1712","Albert"),("1703","Benny"),...]