2017-06-06 192 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')...