我有一个有点奇怪的请求,希望您能以最高效的方式解决它。 我有两个列表list_1和list_2,它们的长度相同,并且都只包含大于或等于0的整数。我想创建一个新列表list_3,使得每个元素i都是来自list_1和list_2位置i处的元素之和。在Python中,可以使用以下代码实现:
list_3 = [list_1[i] + list_2[i] for i in range(len(list_1))]
但是,这里有一个问题。对于所有满足0 <= i < len(list_1)的i,如果位置i处的元素(即list_1[i])为0,则list_1[i]和list_2[i]的和也应该为0。
那么,最有效的方法是什么?我需要对包含323个元素的列表执行此操作,并且需要用于游戏,因此它应该能够轻松运行60次每秒,同时允许很多额外时间计算游戏中的其他内容。我想知道是否有任何花式的numpy方法可以做到这一点,但我对numpy不熟悉,无法确定。
编辑:
关于简单求和的一些常见表达式如下:
但是,这里有一个问题。对于所有满足0 <= i < len(list_1)的i,如果位置i处的元素(即list_1[i])为0,则list_1[i]和list_2[i]的和也应该为0。
那么,最有效的方法是什么?我需要对包含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,并且需要对所有键执行此操作,而不仅仅是选择几个键。根据,它目前相对于程序的其他部分来说是瓶颈。
这里是生成每个键盘键状态的代码(它使用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