30个Python优秀实践和技巧,你值得拥有~
| x = "Success!" if (y== 2) else "Failed!" 25. 计算频率 使用集合库中的Counter来获取包含列表中所有唯一元素计数的字典: from collections import Counter 
 mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6] 
 c = Counter(mylist) 
 print(c) 
 # Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2}) 
 # And it works on strings too: 
 print(Counter("aaaaabbbbbccccc")) 
 # Counter({'a': 5, 'b': 5, 'c': 5}) viewrawcounter.py hosted with ❤ by GitHub 26. 链接比较运算符 在Python中链接比较运算符,以创建更易读和简洁的代码: x =10 
 # Instead of: 
 if x >5and x <15: 
 print("Yes") 
 # yes 
 # You can also write: 
 if5< x <15: 
 print("Yes") 
 # Yes viewrawchaining_comparisons.py hosted with ❤ by GitHub 27. 添加一些颜色 使用Colorama,在终端添加点颜色. from colorama import Fore, Back, Style 
 print(Fore.RED+'some red text') 
 print(Back.GREEN+'and with a green background') 
 print(Style.DIM+'and in dim text') 
 print(Style.RESET_ALL) 
 print('back to normal now') viewrawcolorama.py hosted with ❤ by GitHub 28. 添加日期 python-dateutil模块提供了对标准datetime模块的强大扩展。 通过以下方式安装: pip3 install python-dateutil 您可以使用此库做很多很棒的事情。我只会重点介绍对我来说特别有用的例子:如模糊分析日志文件中的日期等。 from dateutil.parser import parse 
 logline ='INFO 2020-01-01T00:00:01 Happy new year, human.' 
 timestamp = parse(log_line, fuzzy=True) 
 print(timestamp) 
 # 2020-01-01 00:00:01 viewrawdateutil.py hosted with ❤ by GitHub 只需记住:常规的Python日期时间功能不奏效时,python-dateutil就派上用场了! 29. 整数除法 在Python 2中,除法运算符(/)默认为整数除法,除非操作数之一是浮点数。因此,有以下操作: # Python 2 5 / 2 = 2 5 / 2.0 = 2.5 在Python 3中,除法运算符默认为浮点除法,并且//运算符已成为整数除法。这样我们得到: Python 3 5 / 2 = 2.5 5 // 2 = 2 30. 使用chardet进行字符集检测 使用chardet模块来检测文件的字符集。在分析大量随机文本时,这很有用。 安装方式: pip install chardet 现在,有了一个名为chardetect的额外命令行工具,可以像这样使用: chardetect somefile.txt somefile.txt: ascii with confidence 1.0 以上就是2020年30条优秀的代码技巧。我希望您能像享受创建列表一样,享受这些内容。 (编辑:南平站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! | 
