加快lis中价值指标的查找

2024-04-19 21:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

试图找到我们其中一个脚本的瓶颈。你知道吗

if str(fieldvalue) in uniquevalues:
       i = uniquevalues.index(str(fieldvalue))

try/catch周围使用index()会更便宜吗?你知道吗

有没有别的办法让这个便宜点?你知道吗


Tags: in脚本indexiftrystr办法瓶颈
3条回答

另一种选择是不使用列表。字典.get比列表.index快。你知道吗

uniquevalues_d = {k: i for i, k in enumerate(uniquevalues)}
index = uniquevalues_d.get(str(fieldvalue))  #get returns None if the value is not found

在这种情况下使用try/except不仅更便宜,而且更好(特别是对于并发性):

try:
    i = uniquevalues.index(str(fieldvalue))
except ValueError:
    print('not found')

这就是^{}原则:

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

使用set而不是list。它是散列的,是用于此目的的正确对象。你知道吗

uniquevalues = ['honda','toyota','chevy']
uniqueset = set(uniquevalues)
fieldvalue = 'honda'

if str(fieldvalue) in uniqueset:
       i = uniquevalues.index(str(fieldvalue))

print i

如果您只关心包容,而不关心顺序或位置,则会发生变化。你知道吗

uniquevalues = {'honda', 'toyota', 'chevy'}
fieldvalue = 'honda'
i = str(fieldvalue) in uniquevalues
print i

相关问题 更多 >