我有装饰器传递变量'insurance_mode'的问题.我会通过以下装饰器声明来做到这一点:
@execute_complete_reservation(True)
def test_booking_gta_object(self):
self.test_select_gta_object()
Run Code Online (Sandbox Code Playgroud)
但不幸的是,这种说法不起作用.也许有更好的方法可以解决这个问题.
def execute_complete_reservation(test_case,insurance_mode):
def inner_function(self,*args,**kwargs):
self.test_create_qsf_query()
test_case(self,*args,**kwargs)
self.test_select_room_option()
if insurance_mode:
self.test_accept_insurance_crosseling()
else:
self.test_decline_insurance_crosseling()
self.test_configure_pax_details()
self.test_configure_payer_details
return inner_function
Run Code Online (Sandbox Code Playgroud) 我试图numpy.array根据给定的密钥翻译a的每个元素:
例如:
a = np.array([[1,2,3],
[3,2,4]])
my_dict = {1:23, 2:34, 3:36, 4:45}
Run Code Online (Sandbox Code Playgroud)
我想得到:
array([[ 23., 34., 36.],
[ 36., 34., 45.]])
Run Code Online (Sandbox Code Playgroud)
我可以看到如何使用循环:
def loop_translate(a, my_dict):
new_a = np.empty(a.shape)
for i,row in enumerate(a):
new_a[i,:] = map(my_dict.get, row)
return new_a
Run Code Online (Sandbox Code Playgroud)
是否有更高效和/或纯粹的numpy方式?
编辑:
我计时了,np.vectorizeDSM提出的方法对于更大的数组要快得多:
In [13]: def loop_translate(a, my_dict):
....: new_a = np.empty(a.shape)
....: for i,row in enumerate(a):
....: new_a[i,:] = map(my_dict.get, row)
....: return new_a
....:
In [14]: def vec_translate(a, my_dict):
....: return np.vectorize(my_dict.__getitem__)(a)
....:
In [15]: a …Run Code Online (Sandbox Code Playgroud) 运行np.unique()时,它首先展平数组,对数组进行排序,然后查找唯一值.当我的数组具有形状(10,3000,3000)时,需要大约一秒钟来查找唯一身份,但这很快就会增加,因为我需要多次调用np.unique().由于我只关心数组中唯一数字的总数,因此排序似乎是浪费时间.
是否有更快的方法来查找除np.unique()之外的大型数组中的唯一值总数?
假设我有一个昂贵的操作expensive(x: int) -> int和以下列表理解:
# expensive(x: int) -> int
# check(x: int) -> bool
[expensive(i) for i in range(LARGE_NUMBER) if check(expensive(i))]
Run Code Online (Sandbox Code Playgroud)
如果我想避免expensive(i)为每个运行两次i,有什么方法可以通过列表理解来保存它的值?
python performance list-comprehension dictionary-comprehension set-comprehension