首页 / PYTHON / Python高级特性
Python高级特性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python高级特性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1899字,纯文字阅读大概需要3分钟。
内容图文
![Python高级特性](/upload/InfoBanner/zyjiaocheng/643/173449b42d3649dba83b1cd530a84285.jpg)
and & or
在使用or时,比如A or B,当A为真时,将不再计算B
在使用and时,A and B,当A为假时,将不再计算B
zip & map & filter
def pascal(n):
if n == 1:
return [[1]]
else:
result = [[1]]
x = 1
while x < n:
lastRow = result[-1]
nextRow = [(a+b) for a,b in zip([0] + lastRow, lastRow + [0])]
result.append(nextRow)
x += 1
return result
pascal(4) # [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
当x=1时,zip([0] + lastRow, lastRow + [0]) = 前面[0,1]后面[1,0]
当x=2时,zip([0] + lastRow, lastRow + [0]) = 前面[0,1,1]后面[1,1,0]
result8 = list(map(lambda x: x + "ing", ["play", "talk", "walk", "teach"]))
print(result8) # ['playing', 'talking', 'walking', 'teaching']
result11 = list(filter(lambda x: len(x) < 5, ["play", "talk", "walk", "teach"]))
print(result11) # ['play', 'talk', 'walk']
flatten
list_of_lists = [[1,2],[3,4],[5,6]]
print(sum(list_of_lists, [])) # [1, 2, 3, 4, 5, 6]
repr & eval & exec
在编写代码时,一般会使 repr() 数来生成动态的字符串,再传入到 eval() 或 exec() 函数内,实现动态执行代码的功能。
s="hello"
print(repr(s)) # 'hello'
print(str(s)) # hello
生成二维数组的一种方式
graph = list()
for row in range(4):
graph.append([])
for col in range(4):
graph[row].append(0)
g = (x * x for x in range(10))
print(g) # <generator object <genexpr> at 0x00000234C6568840>
next(g) # 0
字典value找key
If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.
在你迭代的过程中如果没有发生对字典的修改,那么keys() and values() 这两个函数返回的 dict-view对象总是保持对应关系
dicxx = {'a':'001', 'b':'002'}
list(dicxx.keys())[list(dicxx.values()).index("001")]
反转字典
old_dict = {'a':'001', 'b':'002','c':'001'}
new_dict = {}
for k,v in old_dict.items():
if not new_dict.get(v):
new_dict[v] = [k]
else:
new_dict[v].append(k)
print(new_dict['001']) # ['a', 'c']
高一少年
发布了34 篇原创文章 · 获赞 4 · 访问量 1571
私信
关注
内容总结
以上是互联网集市为您收集整理的Python高级特性全部内容,希望文章能够帮你解决Python高级特性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。