[英]Saving tuple with numbers to file as string
I'm starting with Python in Machine Learning, I'm interested in solving old Kaggle competition for my own. 我从机器学习中的Python开始,我有兴趣为我自己解决旧的Kaggle竞赛。 First thing I need to do is to convert list of encoded pixels to a bounding box, convert it to have top left and bottom right rectangle coordinates, have it in specific output and save it to a file
我需要做的第一件事是将编码像素列表转换为边界框,将其转换为左上角和右下角矩形坐标,将其保存在特定输出中并将其保存到文件中
I found already examples where using RLE algorithm convert encoded pixels and I need to change it to save to the file. 我找到了使用RLE算法转换编码像素的示例,我需要更改它以保存到文件中。 My particular problem is saving a tuple to a file in
x1,y1,x2,y2
format 我的特殊问题是将元组保存为
x1,y1,x2,y2
格式的文件
I have a code, which takes the first and the last coordinate from the list of pixels. 我有一个代码,它从像素列表中获取第一个和最后一个坐标。 First I tried with:
首先我试过:
f = open("file.txt", "w")
f.write(str(mask_pixels[0]) + str(mask_pixels[len(mask_pixels)-1]))
f.write("\n")
f.close()
But the output is like (469, 344)(498, 447)
(which is a tuple, so that's fine). 但输出就像
(469, 344)(498, 447)
(这是一个元组,所以没关系)。
I tried to use join
function as following: 我尝试使用
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()
But it saves it as (,4,6,9,,, ,3,4,4,)(,4,9,8,,, ,4,4,7,)
但它将它保存为
(,4,6,9,,, ,3,4,4,)(,4,9,8,,, ,4,4,7,)
So I tried with 所以我尝试了
f = open("file.txt", "a")
f.write(str(coordinate1))
f.write(",")
f.write(str(coordinate2))
f.write("\n")
f.close()
But it saves it as (469, 344),(498, 447)
, which is still something I'm not looking for. 但它保存为
(469, 344),(498, 447)
,这仍然是我不想要的东西。 Can anyone show me a hint how should I do it to have in a file something like 469,344,498,447
? 任何人都可以给我一个提示我应该怎么做才能拥有像
469,344,498,447
这样的文件? I'm not asking for a code directly (I know you guys might not have time for it), but I'm looking for an idea what should I read/learn. 我不是直接要求代码(我知道你们可能没有时间),但我正在寻找一个想法,我应该阅读/学习什么。
with open("file.txt", "w") as f:
print(*sum((mask_pixels[0],mask_pixels[-1]),()),sep=', ',file=f)
Output 产量
469, 344, 498, 447
You can transform your tuples in list and concatenate them : 您可以在列表中转换元组并将它们连接起来:
a = (469, 344)
b= (498,447)
result = list(a) + list(b)
Output : 输出:
[469, 344, 498, 447]
To go back to your code it could look something like that : 要回到你的代码,它可能看起来像这样:
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()
And if you want to save all of your mask you could even do a double list comprehension : 如果你想保存所有面具,你甚至可以做双列表理解:
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.