我有以下代码:
print(img.size)
print(10 * img.size)
这将打印:
(70, 70)
(70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70)
我想要打印:
(700, 700)
有没有办法做到这一点,而不必写:
print(10 * img.size[0], 10 * img.size[1])
PS:img.size
是PIL图片。不知道在这种情况下,Dunno是否重要。
答案 0 :(得分:49)
可能是一个更好的方式,但这应该工作
tuple([10*x for x in img.size])
答案 1 :(得分:30)
img.size = tuple(i * 10 for i in img.size)
答案 2 :(得分:13)
pythonic 方式将使用列表解析:
y = tuple([z * 10 for z in img.size])
另一种方式可能是:
y = tuple(map((10).__mul__, img.size))
答案 3 :(得分:7)
解决方案:
set1=(70, 70)
tuple(2*array(set1))
说明:arrays
可以直接进行标量乘法。因此,tuple
此处调用的set1
转换为array
。我假设您希望继续使用tuple
,因此我们会将array
转换回tuple
。
此解决方案是为了避免显式和冗长的for
循环。我不知道它是否更快,或两种情况下是否完全相同。
答案 4 :(得分:2)
可能有一种比这更简单的方法,但是
print map(lambda x: 10*x, img.size)
几乎可以做你想要的,虽然它打印成列表而不是元组。如果要将map
调用打印为元组(括号而不是方括号),请将tuple(map...)
调用包裹在{{1}}内。
答案 5 :(得分:2)
如果你经常遇到这个问题并且有更大的元组或列表,那么你可能想要使用numpy库,它允许你对数组进行各种数学运算。但是,在这种简单的情况下,这将是完全矫枉过正的。
答案 6 :(得分:2)
如果您正在编写一堆代码,但不想要更复杂的矢量库,那就简单了...
class V(tuple):
'''A simple vector supporting scalar multiply and vector add'''
def __new__ (cls, *args):
return super(V, cls).__new__(cls, args)
def __mul__(self,s):
return V( *( c*s for c in self) )
def __add__(self,s):
return V( *( c[0]+c[1] for c in zip(self,s)) )
def __repr__(self):
return "V" + super(V, self).__repr__()
# As long as the "vector" is on the left it just works
xaxis = V(1.0, 0.0)
yaxis = V(0.0, 1.0)
print xaxis + yaxis # => V(1.0, 1.0)
print xaxis*3 + yaxis*5 # => V(3.0, 5.0)
print 3*xaxis # Broke, => (1.0, 0.0, 1.0, 0.0, 1.0, 0.0)
“V”实例的行为就像元组一样。这要求“V”实例都使用相同数量的元素创建。例如,您可以添加到__new__
if len(args)!=2: raise TypeError('Must be 2 elements')
强制所有实例都是2d向量....
答案 7 :(得分:1)
您可以尝试这样的事情:
print [10 * s for s in img.size]
它将为您提供一个新列表,其中包含元组中所有元素乘以10
答案 8 :(得分:1)
与之前的答案一致但使用numpy:
import numpy as np
result = tuple(10*np.array(img.size))
答案 9 :(得分:1)
仅概述
import timeit
# tuple element wise operations multiplication
# native
map_lambda = """
a = tuple(range(10000))
b = tuple(map(lambda x: x * 2, a))
"""
# native
tuple_comprehension = """
a = tuple(range(10000))
b = tuple(x * 2 for x in a)
"""
# numpy
using_numpy = """
import numpy as np
a = tuple(range(10000))
b = tuple((np.array(a) * 2).tolist())
"""
print('map_lambda =', timeit.timeit(map_lambda, number=1000))
print('tuple_comprehension =', timeit.timeit(tuple_comprehension, number=1000))
print('using_numpy =', timeit.timeit(using_numpy, number=1000))
我的计算机上的时间
map_lambda = 1.541315148000649
tuple_comprehension = 1.0838452139996662
using_numpy = 1.2488984129995515
答案 10 :(得分:0)
只添加各种各样的东西..
import operator
img_size = (70, 70)
map(operator.mul, img_size, len(img_size)*(10,))
答案 11 :(得分:0)
您正尝试将该功能应用于整个元组。 您需要将它应用于单个元素并返回一个新元组。
newTuple = tuple([10*x for x in oldTuple])
请记住,您无法更改元组。