将元组乘以标量

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)

  • 稍微好一点:`元组(10*x for x in img.size)` (26认同)

tru*_*ppo 34

img.size = tuple(i * 10 for i 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)

  • 第二个太棒了……哈哈。 (2认同)
  • 这两个例子都没有说明问题的重点.两者都迫使程序员采用一个简单的想法(标量乘以矩阵乘法)并解构它. (2认同)

Mar*_*vin 7

如果您正在编写一堆代码,但不想要更复杂的向量库,那么事情就很简单......

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循环.我不知道它是否更快或两种情况下是否完全相同.

  • 据我所知,这在Python 2或3中不起作用.我假设`array`来自`array`模块?Python期望一个字符作为`array`的第一个参数,因此只传递一个元组将失败,其中`TypeError:array()参数1或typecode必须是char(字符串或ascii-unicode,长度为1),而不是tuple`.你能用一个更完整的例子对此进行扩展吗? (2认同)
  • 我认为它是一个 numpy 数组? (2认同)

spa*_*ers 5

可能有比这更简单的方法,但是

print map(lambda x: 10*x, img.size)
Run Code Online (Sandbox Code Playgroud)

尽管它打印为列表而不是元组,但几乎可以完成您想要的操作。如果您希望将其作为元组打印(括号而不是方括号),请将调用包含map在内。tuple(map...)