2016-05-29 105 views
0

我試圖返回x的列表和閱讀與數字的文本文件,它例如後y座標元組:返回x的名單和y座標元組

68,125 
113,69 
65,86 
108,149 
152,53 

我得在這裏我返回一個數字列表,但不是在一個元組中的對。

這裏是我的代碼:

def read_numbers(filename): 
    numbers = [] 
    input_file = open(filename, "r") 
    content = input_file.readlines() 
    numbers = [word.strip() for word in content] 
    input_file.close() 
    return numbers 
def main(): 
    numbers = read_numbers('output.txt') 
    print(numbers) 

main() 
+0

需要看起來像這樣:[(68,125),(113,69),(65,86),(108,149) ,(152,53)] –

回答

0

您可以閱讀每一行,然後分裂以逗號每一行,並用地圖每一塊分割轉換爲int。最後,將其轉換成元組

coords = [tuple(map(int, line.split(","))) for line in lines] 

這使輸出:

[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53)] 


你完整的代碼可能是這個樣子:

with open("output.txt") as f: 
    lines = f.readlines() 

coords = [tuple(map(int, line.split(","))) for line in lines] 
print(coords) 
+0

感謝您的幫助 –

0

我推薦使用的發生器,它允許你使用額外的控制結構,然後列表理解:

def parse_file(file): 
    for line in file: 
     num1, num2 = line.split(",") #this can't be done in list comprehension 
     yield (int(num1), int(num2)) 

然後你read_numbers看起來是這樣的:

def read_numbers(filename): 
    with open(filename,"r") as f: 
     return list(parse_file(f)) 
+0

感謝您的幫助 –