首页 » Python » 秦路天善智能python学习笔记2-其他基础知识

秦路天善智能python学习笔记2-其他基础知识

 

集合:
列表的计算
a = [1,2,3,4]
b = [2,3,4,5]
set(a) & set(b)
{2,3,4}
set(a) | set(b)
{1,2,3,4,5}
set(a) - set(b)
{1}
set(b) - set(a)
{5}
[1,2,3] > a
False
a = {'name':'qinlu','age':18}
list(a.keys())
['name','age']
list(a.values())
['qinlu',18]
list(a.items())
[('name','qinlu'),('age',18)]
a.get('nam',1)
1
a.getdefault('sex','female')
{'name':'qinlu','age':18,'sex':'female'}

控制流:
a = 10
if a >10:
print('more than 10')
elif a == 10:
print('equal to 10')
else:
print('less than 10')

count = 0
while count < 10: count = count +1 print(count) if count == 5: break count = 0 while count < 10: count = count +1 if count == 5: continue print(count) for i in range(10): print(i) for a in [1,2,3]: print(a) dict = {'a':1,'b':2,'c':3} for k in dict.keys(): print k for v in dict.values(): print k for k,v in dict.items(): print(k) print(v) 循环进阶: list = [] for i in range(1,101): list.append(i) if i % 2 == 0: list2.append(i) list_2 = [i for i in range(1,101)] list_3 = [i for i in range(1,101) if i % 2 == 0] dict = {'a':1,'b':2} [v**2 for v in dict.values() if v % 2 ==0] python函数: def func(x): if x>10:
print('more than 10')
else:
print('less than 10')

def add(x,y):
return x+y
a = add(1,2)

高级函数:
[x**2 for x in range(1,10)]
def func(x):
return x*x
[func(x) for x in range(1,10)]
list(map(func,[1,2,3,4,5,6,7,8,9]))

lambda 匿名函数
list(map(lambda x:x*x,[1,2,3,4,5]))

第三方包:
a = [1,2,3,4,1,2,3.1]
d = {}
for i in a:
if i in d.keys():
d[i] = d[i] + 1
else:
d[i] = 1
import collections
a = [1,2,3,4,1,2,3.1]
dict(collections.Counter(a))
这里实现了使用第三方包来统计a里面各个内容的数量

原文链接:秦路天善智能python学习笔记2-其他基础知识,转载请注明来源!

0