dev*_*ium 48 python python-imaging-library
我有以下代码:
print(img.size)
print(10 * img.size)
Run Code Online (Sandbox Code Playgroud)
这将打印
(70, 70)
(70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70)
Run Code Online (Sandbox Code Playgroud)
虽然我想要它打印
(700, 700)
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点,而不必写
print(10 * img.size[0], 10 * img.size[1])
Run Code Online (Sandbox Code Playgroud)
PS:img.size是一个PIL图像.Dunno,如果在这种情况下重要的话.
Han*_*rén 56
可能是一个更好的方式,但这应该工作
tuple([10*x for x in img.size])
Run Code Online (Sandbox Code Playgroud)
Chr*_*heD 14
在Python的方法是使用列表理解:
y = tuple([z * 10 for z in img.size])
Run Code Online (Sandbox Code Playgroud)
另一种方式可能是:
y = tuple(map((10).__mul__, img.size))
Run Code Online (Sandbox Code Playgroud)
如果您正在编写一堆代码,但不想要更复杂的向量库,那么事情就很简单......
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)
Run Code Online (Sandbox Code Playgroud)
“V”实例的其他行为就像元组一样。这要求“V”实例全部使用相同数量的元素创建。例如,您可以添加到 __new__
if len(args)!=2: raise TypeError('Must be 2 elements')
Run Code Online (Sandbox Code Playgroud)
强制所有实例都是二维向量......
小智 6
解:
set1=(70, 70)
tuple(2*array(set1))
Run Code Online (Sandbox Code Playgroud)
说明:arrays使直接标量乘法成为可能.因此这里被tuple称为set1转换为array.我假设您希望继续使用tuple,因此我们将array返回转换为tuple.
此解决方案是避免显式和详细for循环.我不知道它是否更快或两种情况下是否完全相同.
可能有比这更简单的方法,但是
print map(lambda x: 10*x, img.size)
Run Code Online (Sandbox Code Playgroud)
尽管它打印为列表而不是元组,但几乎可以完成您想要的操作。如果您希望将其作为元组打印(括号而不是方括号),请将调用包含map在内。tuple(map...)