简体   繁体   中英

Multiplying a string with a float

So, I am very new to python but have done a little bit of programming in matlab. So now i have two values that i want to multply by the same constant, for example:

res = 1920, 1080

win_scale = 1/1.25

width, height = res*win_scale

which gives me the error: "can't multiply sequence by non-int of type 'float'"

I have found other related questions but none that I can understand. Thank you

Assuming you want each value in res multiplied by the float:

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

You can't multiply a list by a float. You have to do it with an int. And I don't believe it will output what you want.

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

What you are looking for I think is element-wise multiplication which you can do with list like this

a = [i * 2 for i in a]

But the best option would be to use a Numpy array by importing the library. Numpy array supported this type of element wise operation and you can do in fact

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

You can just try to convert res to a numpy array. That would allow you to multiply a number with the array's items in just a single line without the need of an loops.

Just do this.

import numpy as np

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

Output -

(1536.0, 864.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM