原文:https://docs.quantifiedcode.com/python-anti-patterns/performance/using_key_in_list_to_check_if_key_is_contained_in_a_list.html 使用 key in list 去迭代list会潜在的花费n次迭代才能完成,n为该key在list中位置.允许的话,可以将list转成set或者dict, 因为Python在set或dict中查找元素是通过直接访问他们而不需要迭代,这会高效很
判断值是否在set集合中的速度明显要比list快的多, 因为查找set用到了hash,时间在O(1)级别. 假设listA有100w个元素,setA=set(listA)即setA为listA转换之后的集合. 以下做个简单的对比: for i in xrange(0, 5000000): if i in listA: pass for i in xrange(0, 5000000): if i in setA: pass 第一个循环用了16min,第二个循环用了52s. 由此可见,在set中判断
解决:Python如何判断字符串中是否有中文 In [240]: s Out[240]: '你好aa' In [241]: for i in s: ...: if u'\u4e00' <= i <= u'\u9fff': ...: print("yes") ...: else: ...: print("no") yes yes no no
小测试 in del.py import datetime cur = datetime.datetime.now() num = 1 a_list = {"a":1, "b":2, "c":3} while num < 100000: if "a" in a_list: pass num += 1 now = datetime.datetime.now() print (now - cur).total_seconds
d = {: , : , : , : , : , : } def is_key_present(x): if x in d: print('Key is present in the dictionary') else: print('Key is not present in the dictionary') is_key_present() is_key_present()
下面是我写的python的一个小脚本,作用是:判断文本中的用户名在数据库中是否存在,存在返回1,不存在返回0.用的是MySQL数据库. 要注意的是:strip函数的使用,该函数的作用是去除字符串两端多余的whitespace. 所以strip的作用肯定不是像书上说的去除字符串两端多余空格. 查了一下文档说 Return a copy of the string with the leading and trailing characters removed. The chars argument