相关疑难解决方法(0)

当`starmap`可能优于`List Comprehension`

在回答Clunky计算增量数字之间差异的问题时,是否有更美妙的方法?,我想出了两个解决方案,一个List Comprehension和另一个使用list comprehension.

对我来说,starmapSyntax看起来更清晰,可读,更简洁,更Pythonic.但仍然List Comprehension在itertools中可用,我想知道,必须有一个理由.

我的问题是什么时候There should be one-- and preferably only one --obvious way to do it.可以优先考虑LC

注意如果它是Style的问题那么它肯定是矛盾的LC

头对头比较

可读性很重要.---starmap

它再次成为一种感知问题,但对我starmap来说更具可读性operator.要使用lambda,您需要导入multi-variable,或定义itertools或显式LC功能,然而从中进行额外导入List Comprehension.

表现 ---list comprehension

>>> def using_star_map(nums):
    delta=starmap(sub,izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)
>>> def using_LC(nums):
    delta=(x-y for x,y in izip(nums[1:],nums))
    return sum(delta)/float(len(nums)-1)
>>> nums=[random.randint(1,10) for …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-itertools

7
推荐指数
2
解决办法
3745
查看次数

以元组的形式传递多个参数

我正在传递大量数据;具体来说,我试图将函数的输出传递给一个类,并且输出包含一个具有三个变量的元组。我不能像在输入参数中那样直接将我的函数(元组)的输出传递到类中。

如何格式化元组,使其在没有 的情况下被班级接受input_tuple[0], input_tuple[1], input_tuple[2]

这是一个简单的例子:

#!/usr/bin/python

class InputStuff(object):

    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c


input_tuple = (1, 2, 3)
instance_1 = InputStuff(input_tuple)

# Traceback (most recent call last):
#   File "Untitled 3.py", line 7, in <module>
#     instance_1 = InputStuff(input_tuple)
# TypeError: __init__() takes exactly 4 arguments (2 given)

InputStuff(1, 2, 3)
# This works
Run Code Online (Sandbox Code Playgroud)

python arguments tuples class object

3
推荐指数
1
解决办法
5837
查看次数

如何将元组作为参数传递给 Lua 函数?

有没有办法将元组作为 Lua 函数的参数传递?

例如,我有一个返回多个值的函数

function f(a,b)  return b,a end
Run Code Online (Sandbox Code Playgroud)

我希望这个功能f被重复应用,所以我可以写:

f (f ... f(1,2))
Run Code Online (Sandbox Code Playgroud)

但是如果我需要将这个初始元组存储(1,2)为一个变量init呢?

f (f ... f(init))
Run Code Online (Sandbox Code Playgroud)

是否有支持?

根据这个答案,python 似乎将它与 splat 运算符一起使用*

lua tuples function

3
推荐指数
1
解决办法
7983
查看次数