使用另一个列表创建坐标列表(类型错误:并非所有参数在字符串格式化期间转换)



我正在尝试使用另一个列表制作一个包含坐标的列表,如下所示:

test = ['62r', '29a', '8v', '52b', '59c', '37n', '35n', '48r', '12n', '49m', '4a', '23a', '21r', '31r', '45r', '36a', '58g', '6e', '15b']
redHeights = []
for value in test:
if 'r' in value:
redHeights.append(value[:-1])
def coordinates(height):
width = 8
coord = x, y = (height%width), (int(height/width))
return coord
newRedChannel = [coordinates(height) for height in redHeights]
print(newRedChannel, 'n')

但是由于某种原因,我收到此错误:

Traceback (most recent call last):
File "C:UsersDavidDesktopRandomizing FunctionDecrypter1.py", line 13, in <module>
newRedChannel = [coordinates(height) for height in redHeights]
File "C:UsersDavidDesktopRandomizing FunctionDecrypter1.py", line 13, in <listcomp>
newRedChannel = [coordinates(height) for height in redHeights]
File "C:UsersDavidDesktopRandomizing FunctionDecrypter1.py", line 10, in coordinates
coord = x, y = (height%width), (int(height/width))
TypeError: not all arguments converted during string formatting

我该如何解决?

在进行除法的其余部分之前,您需要将height(str(转换为int。例如,在newRedChannel列表理解中:

test = ['62r', '29a', '8v', '52b', '59c', '37n', '35n', '48r', '12n', '49m', '4a', '23a', '21r',
'31r', '45r', '36a', '58g', '6e', '15b']
redHeights = []
for value in test:
if 'r' in value:
redHeights.append(value[:-1])

def coordinates(height):
width = 8
coord = (height % width), (height / width)
return coord

newRedChannel = [coordinates(int(height)) for height in redHeights]
print(newRedChannel, 'n')

输出:

[(6, 7.75), (0, 6.0), (5, 2.625), (7, 3.875), (5, 5.625)] 

您的问题在于height属于str类型,因此您必须在使用它执行任何数字运算之前转换为int。您还可以高度简化代码,如下所示:

redHeights = [value[:-1] for value in test if 'r' in value]
newRedChannel = [((int(height) % 8), (int(height) / 8)) for height in redHeights]

这会产生:

[(6, 7.75), (0, 6.0), (5, 2.625), (7, 3.875), (5, 5.625)]

我所要做的就是添加这个:

redHeights = list(map(int, redHeights))

我没有意识到我确实这样做了,但我在一个我完全错过的print方法中写了那行,这让我完全摆脱了*极端数量的面部*:

print(list(map(int, redHeights)))

最新更新