簡體   English   中英

如何從 a.txt 文件中讀取值並將它們保存到 python 中的不同變量中並訪問它們?

[英]How can I read values from a .txt-file and save them into different variables in python and get access to them?

我是新的學習編碼。 我正在嘗試讀取包含多行的文件。 線條具有 x,y 坐標值。 最后一個數字 z 是一些隨機數額的錢。 我想將它們保存在列表中的不同變量中。 例如,我的.txt-file是這樣的,只是多了幾百行:

0,3,97.72  
0,4,97.69  
0,5,97.66  

我希望它逐行保存,如下所示: x = 0 y = 3 z = 97.72

當我然后 select 兩個隨機坐標時,我想得到它們之間的所有坐標和 plot 所有 z 值與matplotlib 我怎樣才能做到這一點?

我試圖用 for 循環保存值,但失敗了。 編輯:這是我的嘗試:

with open(f"example.txt", "r", encoding=ascii) as lines:
    coordinates=[]
    for line in lines:
        x_text,y_text, z_text = line.split(",")
        coordinates.append((int(x_text), int(y_text), float(z_text)))

for x, y  in coordinates:
    if x_text ==x and y_text <= y <=y_text:
        print()
    elif x_text <= x <=x_text and y_text == y:
        print()      

您似乎能夠將文件數據讀入坐標列表,因此我假設您的問題在於確定給定坐標是否在某種邊界框內。

嘗試:

def falls_between(coord, top_left, bottom_right):
    return top_left[0] <= coord[0] <= bottom_right[0] and top_left[1] <= coord[1] <= bottom_right[1]

test_top_left = (0, 0)
test_bottom_right = (4, 4)
coordinates=[]
with open("in.csv", "r") as file_in:
    for row in file_in:
        x, y, z = row.strip("\n").split(",")
        coordinates.append([int(x), int(y), float(z)])

for coord in coordinates:
    if falls_between(coord, test_top_left, test_bottom_right):
        print(f"{coord} is inside {test_top_left} and {test_bottom_right}")
    else:
        print(f"{coord} is not inside {test_top_left} and {test_bottom_right}")

暫無
暫無

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

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