簡體   English   中英

我需要從文件中獲取x,y坐標的元組並將其添加到列表中

[英]I need to get tuples of x,y coordinates from a file and add it to a list

所以我的txt文件看起來像這樣:

68,125
113,69
65,86
108,149
152,53
78,90
54,160
20,137
107,90
48,12

我需要閱讀這些文件,然后將其放入x和y坐標元組的列表中。

我的輸出應該是

[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53), (78, 90), (54, 160), (20, 137), (107, 90), (48, 12)] 

我被困在如何做到這一點上。 我只需要使用基本的python。

編輯:

到目前為止,我的嘗試是

numbers = []
input_file = open(filename,'r')
numbers_list = input_file.readlines()
input_file.close()
for i in numbers_list:
    numbers += [i]
return numbers

我的輸出返回如下:

['68,125\n', '113,69\n', '65,86\n', '108,149\n', '152,53\n', '78,90\n', '54,160\n', '20,137\n', '107,90\n', '48,12\n']

如何擺脫'\\ n'以及如何將列表中的每個元素放入一個元組。 謝謝。 我沒有加入嘗試的錯誤。

這是3和2行答案:

with open("my_txt_file") as f:
  lines = f.readlines()
result = [tuple(int(s) for s in line.strip().split(",")) for line in lines]

就像IljaEverilä指出的那樣,“打開文件作為迭代器”更好:

with open("my_txt_file") as f:
  result = [tuple(int(s) for s in line.strip().split(",")) for line in f]

從文件中換行讀取所有內容。 從每個字符串中刪除換行符。 然后通過用逗號分割將每個字符串轉換為元組。 以下是帶有文本文件輸入的代碼,其中包含您所要求的內容和預期的結果。

import sys
def test(filename):
    f = open(filename)
    lines = f.readlines()
    lines = [item.rstrip("\n") for item in lines]
    newList = list()
    for item in lines:
            item = item.split(",")
            item = tuple(int(items) for items in item)
            newList.append(item)                
    f.close()
    print newList

if __name__ == "__main__":
    test(sys.argv[1])

O/P:
techie@gateway2:myExperiments$ python test.py /export/home/techie/myExperiments/test.txt
[(68, 125), (113, 69), (65, 86), (108, 149), (152, 53), (78, 90), (54, 160), (20, 137), (107, 90), (48, 12)]

希望這會有所幫助。 :-)

由於文件包含逗號分隔的整數值,因此可以使用csv模塊來處理它:

import csv

with open(filename, newline='') as f:
    reader = csv.reader(f)
    numbers = [tuple(map(int, row)) for row in reader]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM