2017-06-06 223 views
0

下面是我在文本文件中:如何将列表转换为元组列表?

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 

这里是输出应该是:

Output file

回答

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')) 
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

只要打开该文件,然后分割这些行,我意识到,你所需要的结果就像(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')] 
+1

需要的输出是(INT,字符串)对,而不是一个(字符串,字符串) –

+0

@JonKiparsky我意识到,我会更新它。 – McGrady

-2
Location = ["1712","1703","1799",...] 
Name = ["Albert","Benny","Henry",...] 

z = zip(Location, Name) 
print z 

输出:

[("1712","Albert"),("1703","Benny"),...] 
+0

需要的输出是一个(INT,字符串)对,而不是一个(字符串,字符串) –

+0

另外,输入来自文件,而不是一对列表 –

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 
+0

的请注意所需的输出格式是(INT,字符串),而不是(串,字符串) –

+0

@JonKiparsky感谢的是,我改进我的答案。 – Daniel

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,当它们变得更加复杂时避免它们。 (或者当他们需要你计算相同的值的两倍)

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')...