from random import randint
data = [randint(-10,10) for _ in range(10)]
data
# 篩選出列表中大於0的元素
# 使用filter函數
list(filter(lambda x:x>=0,data))
# 列表解析
[x for x in data if x >= 0]
timeit list(filter(lambda x:x>=0,data))
timeit [x for x in data if x >= 0]
# 字典解析
d = {x:randint(60,100) for x in range(1,21)}
d
{k:v for k,v in d.items() if v > 90 }
# 集合解析
s = set(data)
s
{x for x in s if x % 2 == 0}
#方案一,定義一系列數值常量
NAME,AGE,SEX,EMAIL = range(4)
student = ('Tom','16','male','tom@gmail.com')
student[NAME]
#方案二,使用namedtuple
from collections import namedtuple
Student = namedtuple('Student',['name','age','sex','email'])
#位置傳參
s = Student('Tom','16','male','tom@gmail.com')
s
#關鍵字傳參
s2 = Student(name='Tom',age='16',sex='male',email='tom@gmail.com')
s2
s.name
s.email
isinstance(s,tuple)
from random import randint
data = [randint(0,20) for _ in range(30)]
data
#fromkeys:用於建立並返回一個新的字典。兩個參數:第一個是字典的鍵,第二個(可選)是傳入鍵的值,默認爲None。
c = dict.fromkeys(data,0)
c
for x in data:
c[x] += 1
c
# 使用Counter
from collections import Counter
c2 = Counter(data)
c2
#找出頻率出現最高的3個元素
c2.most_common(3)
import re
txt = open('Alice.txt').read()
c3 = Counter(re.split('\W+',txt))
c3
c3.most_common(10)
sorted([9,3,1,67,6])
from random import randint
d = {x:randint(60,100) for x in 'xyzabc'}
d
d.keys()
d.values()
#方案一:利用zip將字典轉換成元組進行排序
sorted(zip(d.values(),d.keys()))
d.items()
#方案二:傳遞sorted函數的key參數
sorted(d.items(),key=lambda x:x[1])
from random import randint,sample
from random import randint,sample
# 取樣
sample('abcdef',3)
sample('abcdef',randint(3,6))
# 找出s1,s2,s3中都存在的key
# 方案一:遍歷
s1 = {x:randint(1,4) for x in sample('abcdef',randint(3,6))}
s1
s2 = {x:randint(1,4) for x in sample('abcdef',randint(3,6))}
s3 = {x:randint(1,4) for x in sample('abcdef',randint(3,6))}
s2
s3
res = []
for k in s1:
if k in s2 and k in s3:
res.append(k)
res
# 方案二:使用集合
s1
s1.keys()
s2.keys()
s1.keys() & s2.keys() & s3.keys()
# 方案三:使用map和reduce
# Python3裏,map返回的結果是迭代器(iterator)
list(map(dict.keys,[s1,s2,s3]))
from functools import reduce
# reduce() 函數會對參數序列中元素進行累積。
reduce(lambda a,b:a & b,map(dict.keys,[s1,s2,s3]))
d = {}
d['Tom'] = (1,35)
d['Bob'] = (2,37)
d['Kate'] = (3,45)
d
# python3.6以後字典有序,按照數據存入的順序
for k in d:
print(k)
# 有序字典OrderedDict
from collections import OrderedDict
d = OrderedDict()
d['Tom'] = (1,35)
d['Bob'] = (2,37)
d['Kate'] = (3,45)
for k in d:
print(k)
from time import time
from random import randint
from collections import OrderedDict
d = OrderedDict()
players =list('ABCDEFGH')
start = time()
for i in range(8):
'''模擬選手比賽消耗時間並存入字典中'''
input()
p = players.pop(randint(0,7-i))
end = time()
print(i + 1, p, end - start,sep=' ')
d[p] = (i + 1, end - start)
print('-' * 30)
for k in d:
print(k, d[k])
from collections import deque
# 建立雙向隊列
q = deque([], 5)
q
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
q
q.append(6)
q
from random import randint
from collections import deque
N = randint(0, 100)
history = deque([], 5)
def guess(k):
if k == N:
print('Right')
return True
if k < N:
print('%s is less-than N' % k)
else:
print('%s is greater-than N' % k)
return False
while True:
line = input('Please input a number:')
if line.isdigit():
k = int(line)
history.append(k)
if guess(k):
break
elif line == 'history' or line == 'h':
print(list(history))
import pickle
q
# 將數據存入文件
pickle.dump(q,open('history','wb'))
# 讀取文件
q2 = pickle.load(open('history','rb'))
q2