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.
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
另一种选择是不使用列表。字典
.get
比列表.index
快。你知道吗在这种情况下使用
try
/except
不仅更便宜,而且更好(特别是对于并发性):这就是^{} 原则:
使用
set
而不是list。它是散列的,是用于此目的的正确对象。你知道吗如果您只关心包容,而不关心顺序或位置,则会发生变化。你知道吗
相关问题 更多 >
编程相关推荐