繁体   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