簡體   English   中英

使用數字保存元組以文件為字符串

[英]Saving tuple with numbers to file as string

我從機器學習中的Python開始,我有興趣為我自己解決舊的Kaggle競賽。 我需要做的第一件事是將編碼像素列表轉換為邊界框,將其轉換為左上角和右下角矩形坐標,將其保存在特定輸出中並將其保存到文件中

我找到了使用RLE算法轉換編碼像素的示例,我需要更改它以保存到文件中。 我的特殊問題是將元組保存為x1,y1,x2,y2格式的文件

我有一個代碼,它從像素列表中獲取第一個和最后一個坐標。 首先我試過:

f = open("file.txt", "w")
f.write(str(mask_pixels[0]) + str(mask_pixels[len(mask_pixels)-1]))
f.write("\n")
f.close()

但輸出就像(469, 344)(498, 447) (這是一個元組,所以沒關系)。

我嘗試使用join函數如下:

coordinates = mask_pixels[0], mask_pixels[len(mask_pixels)-1]
f = open("file.txt", "w")
for x in coordinates:
    f.write(",".join(str(x)))
f.write("\n")
f.close()

但它將它保存為(,4,6,9,,, ,3,4,4,)(,4,9,8,,, ,4,4,7,)

所以我嘗試了

f = open("file.txt", "a")
f.write(str(coordinate1))
f.write(",")
f.write(str(coordinate2))
f.write("\n")
f.close()

但它保存為(469, 344),(498, 447) ,這仍然是我不想要的東西。 任何人都可以給我一個提示我應該怎么做才能擁有像469,344,498,447這樣的文件? 我不是直接要求代碼(我知道你們可能沒有時間),但我正在尋找一個想法,我應該閱讀/學習什么。

with open("file.txt", "w") as f:
    print(*sum((mask_pixels[0],mask_pixels[-1]),()),sep=', ',file=f)

產量

469, 344, 498, 447

您可以在列表中轉換元組並將它們連接起來:

a = (469, 344)
b= (498,447)
result = list(a) + list(b)

輸出:

[469, 344, 498, 447]

要回到你的代碼,它可能看起來像這樣:

f = open("file.txt", "w")
f.write(str(list(str(mask_pixels[0])) + list(str(mask_pixels[len(mask_pixels)-1]))))
f.write("\n")
f.close()

如果你想保存所有面具,你甚至可以做雙列表理解:

a = (469, 344)
b= (498,447)
c = (512,495)
list_of_tuples = [a, b, c]
result = [item for sublist in list_of_tuples for item in sublist]

Out : [469, 344, 498, 447, 512, 495]

暫無
暫無

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

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