python - 在 python 中将两个项目列表相互求和的最快方法

标签 python list numpy

我有一个奇怪的请求,希望以最高效率解决;我有两个列表 list_1list_2 ,它们的长度相同,并且都只包含大于或等于 0 的整数。我想创建一个新列表 list_3这样每个元素 i是位置 i 处元素的总和来自 list_1list_2 .在 python 中,这就足够了:

list_3 = [list_1[i] + list_2[i] for i in range(len(list_1))]

但是,有一个问题。对于每个 i这样 0 <= i < len(list_1) , 如果项目位于 i (即 list_1[i] )为 0,则 list_1[i] 之和和 list_2[i]应该也为零

最有效的方法是什么?我必须在包含 323 个元素的列表上执行此操作,并且它需要用于游戏,因此它应该能够轻松地每秒运行 60 次,同时允许大量额外时间在游戏中计算其他内容。我想知道是否有任何奇特的 numpy 方法可以做到这一点,但我对 numpy 的精通程度不足以确定。

编辑:

就两个元素的简单求和而言,一些常见的表达方式是:

list_3 = [list_1[i] + list_2[i] for i in range(len(list_1))]
list_3 = [sum(t) for t in zip(list_1, list_2)]
list_3 = numpy.add(list_1, list_2)

编辑 2:

我知道条件列表理解,但我想知道是否有比这更快的方法。

编辑 3:

以下是给出的一些方法的时间安排:

>>> import timeit
>>> setup='''
import random
list_1 = [random.randint(0, 323) for i in range(323)]
list_2 = [random.randint(0, 323) for i in range(323)]
'''
>>> timeit.timeit('list_3 = [list_1[i] + list_2[i] if list_2[i] else 0 for i in range(len(list_1))]', setup=setup, number=1)
6.005677381485953e-05
>>> timeit.timeit('list_3 = [x + y if y else 0 for x, y in zip(list_1, list_2)]', setup=setup, number=1)
3.604091037417601e-05

还有更快的吗?

编辑 4:

这里是关于我需要这个的解释:我正在开发一个视频游戏,它需要一个系统来不时检查键盘上某些键的状态。系统需要工作的方式是按下一个键的时间越长,该键的计数器增加得越高。释放该键后,计数器将设置回 0。这需要对所有键完成,而不仅仅是选定的几个键。根据 cProfile,与程序的其余部分相比,它目前是一个瓶颈。 .

这是生成键盘中每个键状态的代码(它使用 pygame 来获取键状态):

class KeyState:
    """
    An object representing the state of the keyboard input at a given frame.

    The KeyState is a global replacement for pygame's event system (or
    pygame.keys.get_pressed()). It provides a simple interface for updating
    and retreiving the states of keys in real time.

    To retreive and store the current key information, simply call
    the update() method. To retreive the given information about a
    key, use the get_state(key) method where key is any pygame key
    (i.e. pygame.K_RSHIFT, etc.).
    """

    def __init__(self):
       self.current_frame = pygame.key.get_pressed()

    def update(self):
        """
        Retreive the current key state data.
        """
        new_frame = pygame.key.get_pressed()
        self.current_frame = [state + new_frame[i] if new_frame[i] else 0 for i, state in enumerate(self.current_frame)]

    def get_state(self, key, strict=True):
        """
        Retreive the current state of a given key.

        >= 1 - Pressed
        0    - Unpressed
        """
        try: 
            return self.current_frame[key]
        except KeyError:
            if strict:
                raise

最佳答案

the longer a key is pressed down, the higher a counter for said key increases

除非您的用户有 300 根手指,否则他们可能一次最多只能按 10 个键。您可以注册 keydown 和 keyup 事件;当按键按下时,将帧计数器或 time()/clock() 的返回值保存在数组中;当一个键启动或当你需要找到键的当前值时,减去差异。这会将循环次数减少到 10 次左右,而不是 300 次。请注意,根据系统的不同,time()/clock() 可能是系统调用,这可能很慢,因此使用帧计数器可能更可取。

counter = 0
keys = {}
while True:
    for event in pygame.event.get() :
        if event.type == pygame.KEYDOWN :
            keys[event.key] = counter
        elif event.type == pygame.KEYUP :
            diff[event.key] = keys.pop(event.key) - counter
    counter += 1

但我非常怀疑这是您游戏的瓶颈。

关于python - 在 python 中将两个项目列表相互求和的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23582663/

相关文章:

python - 流图与 mggrid 不匹配

python - 追加到字典中的列表

python - 在 Ubuntu 12.10 上降级/卸载 numpy

python - 傅立叶变换 2D 工件 - 我做错了什么?

python - 为什么 numpy 可以保存和加载不同于 numpy 数组的对象

python - Python 中一张图中的停留图

python - 在带有 "WITH"关键字的 python 中使用 sqlite3

python - 根据图像 python 内的边框裁剪图像

python - 在不知道内部列表数量的情况下遍历列表列表

algorithm - Lisp:如何从列表中包含的列表中获取元素的所有可能组合?