PYTHON中对列表以及字典的处理小技巧有哪些,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
#if 语句在行内print "Hello" if True else "World">>> Hello#向下取整print 5.0//2>>> 2# 2的5次方print 2**5>> 32#浮点数的除法print .3/.1>>> 2.9999999999999996print .3//.1>>> 2.0#两个列表同时迭代nfc = ["Packers", "49ers"]afc = ["Ravens", "Patriots"]for teama, teambin zip(nfc, afc): print teama + " vs. " + teamb>>> Packers vs. Ravens>>> 49ers vs. Patriots#带索引的列表迭代teams = ["Packers", "49ers", "Ravens", "Patriots"]for index, teamin enumerate(teams): printindex, team>>> 0 Packers>>> 1 49ers>>> 2 Ravens>>> 3 Patriots#用下面的代替numbers = [1,2,3,4,5,6]even = [number for numberin numbers if number%2 == 0]#字典推导teams = ["Packers", "49ers", "Ravens", "Patriots"]print {key: value for value, keyin enumerate(teams)}>>> {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}#初始化列表的值items = [0]*3print items>>> [0,0,0]#将列表转换成字符串teams = ["Packers", "49ers", "Ravens", "Patriots"]print ", ".join(teams)>>> 'Packers, 49ers, Ravens, Patriots'#不要用下列的方式data = {'user': 1, 'name': 'Max', 'three': 4}try: is_admin = data['admin']except KeyError: is_admin = False#替换为data = {'user': 1, 'name': 'Max', 'three': 4}is_admin = data.get('admin', False)
关于PYTHON中对列表以及字典的处理小技巧有哪些问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网行业资讯频道了解更多相关知识。