更多课程 选择中心

Python培训
美国上市教育机构

400-111-8989

Python培训

Python那些简单漂亮的写法举例

  • 发布:Python培训
  • 来源:练习题库
  • 时间:2017-08-25 16:18


Python之禅中有两句话,漂亮好于丑陋,简单好于复杂,下面来举些日常编程中经常会用到的语法的例子。

列表迭代写法

# 方案不可取for i in [0, 1, 2, 3, 4, 5]: print i**2# 方案可取for i in range(6): print i**2# 方案可取,和range不同在于,xrange是生成器for i in xrange(6): print i**2

colors = ["red", "green", "blue", "yellow"]# 方案不可取for i in range(len(colors)): print colors[i]# 方案可取for color in colors: print color# 方案不可取for i in range(len(colors)-1, -1, -1): print colors[i]# 方案可取for color in reversed(colors): print color# 方案不可取for i in range(len(colors)): print i, "-->", colors[i]# 方案可取for i, color in enumerate(colors): print i, "-->", color

import itertoolsnames = ["raymond", "rachel", "matthew"]colors = ["red", "green", "blue", "yellow"]# 方案不可取n = min(len(names), len(colors))for i in range(n): print(names[i], "-->", colors[i])# 方案可取for name, color in zip(names, colors): print(name, "-->", color)# 方案可取for name, color in itertools.izip(names, colors): print(name, "-->", color)

列表排序写法

colors = ["red", "green", "blue", "yellow"]# 方案可取for color in sorted(colors): print color# 方案可取for color in sorted(colors, reverse=True): print color# 方案不可取def compare_length(c1, c2): if len(c1) < len(c2): return -1 if len(c1) > len(c2): return 1 return 0print sorted(colors, cmp=compare_length)# 方案可取print sorted(colors, key=len)

for…else…语法

#方案不可取def find(seq, tgt): found = False for i, value in enumerate(seq): if value == tgt: found = True break if not found: return -1 return 1#方案可取def find(seq, tgt): for i, value in enumerate(seq): if value == tgt: break else: return -1 return 1

字典取值写法

d = {"matthew": "blue", "rachel": "green", "raymond": "red"}# 方案不可取for k in d: print k, "-->", d[k]# 方案可取for k, v in d.items(): print k, "-->", v# 方案可取for k, v in d.iteritems(): print k, "-->", v

字典生成写法

import collectionscolors = ["red", "green", "red", "blue", "green", "red"]# 方案不可取d = {}for color in colors: if color not in d: d[color] = 0 d[color] += 1# 方案可取d = {}for color in colors: d[color] = d.get(color, 0) + 1# 方案可取d = collections.defaultdict(int)for color in colors: d[color] += 1

import collectionsnames = ["raymond", "rachel", "matthew", "roger", "betty", "melissa", "judith", "charlie"]# 方案不可取d = {}for name in names: key = len(name) if key not in d: d[key] = [] d[key].append(name)# 方案可取d = {}for name in names: key = len(names) d.setdefault(key, []).append(name)# 方案可取d = collections.defaultdict(list)for name in names: key = len(name) d[key].append(name)

上下文管理器读取文件写法

# 方案不可取f = open("data.txt")try: data = f.read()finally: f.close()# 方案可取with open("data.txt") as f: data = f.read()

线程锁写法

import threadinglock = threading.Lock()# 方案不可取lock.acquire()try: print "Critical section 1" print "Critical section 2"finally: lock.release()# 方案可取with lock: print "Critical section 1" print "Critical section 2"

输出流写法

import sys# 方案不可取with open("help.txt", "w") as f: oldstdout = sys.stdout sys.stdout = f try: help(pow) finally: sys.stdout = oldstdout# 方案可取,此为Python3之后才支持的功能import contextlibwith open("help.txt", "w") as f: with contextlib.redirect_stdout(f): help(pow)

预约申请免费试听课

填写下面表单即可预约申请免费试听!怕钱不够?可就业挣钱后再付学费! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:零基础小白如何入门 Python 编程
下一篇:Python入门技巧全览

Python编程练习题二

Python编程练习题一

Python实现降雪效果

Python中dir()、help()的使用

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省