将字符串与浮点数相乘

Multiplying a string with a float

所以,我是 python 的新手,但已经在 matlab 中进行了一些编程。所以现在我有两个值,我想乘以相同的常数,例如:

res = 1920, 1080

win_scale = 1/1.25

width, height = res*win_scale

这给了我错误: “不能将序列乘以 'float' 类型的非整数”

我找到了其他相关问题,但none我能理解。谢谢

假设您希望 res 中的每个值乘以浮点数:

width, height = [x * win_scale for x in res]

您不能将列表乘以浮点数。你必须用一个int来做。而且我不相信它会输出你想要的。

a = [1920, 1080]
# Doing a * 2 will output you [1920, 1080, 1920, 1080]

我想你要找的是 element-wise 乘法,你可以用这样的列表来做

a = [i * 2 for i in a]

但最好的选择是通过导入库来使用 Numpy 数组。 Numpy 数组支持这种类型的元素明智的操作,事实上你可以做到

import numpy as np 
a = np.array([1920, 180])
a * 2 # This will give you a = [3840, 2160]

您可以尝试将 res 转换为 numpy 数组。这将允许您在一行中将一个数字与数组的项目相乘,而无需循环。

就这样做吧。

import numpy as np

width, height = np.array(res) * win_scale
print(width, height)

输出-

(1536.0, 864.0)