【问题标题】:remove tuple brackets for .ppm file删除 .ppm 文件的元组括号
【发布时间】:2021-04-23 02:39:11
【问题描述】:

我有这段代码应该反转.ppm 图像的像素。

我能够反转像素,但我一直在删除列表和元组括号列表,以便仅获取整数。

我想要:

 0  0  0  0  0  0    0  0  0   15  0 15
 0  0  0  0 15  7    0  0  0    0  0  0
 0  0  0  0  0  0    0 15  7    0  0  0
15  0 15  0  0  0    0  0  0    0  0  0

我得到了什么:

('15', '0', '15') ('0', '0', '0') ('0', '0', '0') ('0', '0', '0')
('0', '0', '0') ('0', '0', '0') ('0', '15', '7') ('0', '0', '0')
('0', '0', '0') ('0', '15', '7') ('0', '0', '0') ('0', '0', '0')
('0', '0', '0') ('0', '0', '0') ('0', '0', '0') ('15', '0', '15')

代码:

takePPM = input("Enter the pmm file name: ")
try:
    openFile = open(takePPM, "r")
    readFile = openFile.readlines()
except FileNotFoundError:
    print("File not found")
    exit(1)
lists = []
for row in readFile[3:]:
    lists.append(row.split())

#convert each list in lists to lists of 3-tuples
target = []
for list in lists:
    target.append([tuple(list[i:i+3]) for i in range(0,len(list),3)])
revList = []
for i in reversed(target):
    revList.append(i)

#newFile = open("Mirror_" + takePPM, "w")
for row in revList:
    #newFile.write(*row)
    removeList = tuple(row)
    print(*removeList)

注释行是将新的反转像素打印到新文件中,但想先检查一下我得到了正确的格式

【问题讨论】:

  • ''.join(list[i:i+3]) 可能在列表理解中
  • 是的,这行得通,非常感谢你????

标签: python python-3.x list file tuples


【解决方案1】:

您可以将最后一行代码 print(*removeList) 替换为

print(' '.join(''.join(t) for t in removeList))

测试一下:

revList = [[('15', '0', '15'), ('0', '0', '0'), ('0', '0', '0'), ('0', '0', '0')]]
for row in revList:
     #newFile.write(*row)
     removeList = tuple(row)
     print(' '.join(''.join(t) for t in removeList))

# 15015 000 000 000

【讨论】:

  • 我已经编辑了“我想要的部分”,显然这是它应该是的.. 抱歉这个错误。同样,当我输入.ppm 文件时,我会得到原始图片颠倒的 3 张黑白照片。你知道如何解决它吗?
  • 可能是 print(' '.join(' '.join(t) for t in reversed(removeList))) ,第一行是 0 0 0 0 0 0 0 0 0 15 0 15
猜你喜欢
  • 2018-05-13
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多