标签:Python list 高级 特性 001 dict print new lastRow
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,list,高级,特性,001,dict,print,new,lastRow 来源: https://blog.csdn.net/qq_43658387/article/details/104435651
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。