# coding: utf-8
import math
# 一、條件表達式x = -5
log_val = math.log(x) if x > 0 else float('nan')
print(log_val)
# 二、列表推導式
print('找出1000內的偶數(列表推導式):')
l1 = [i for i in range(1000) if i % 2 == 0]
print(l1)
# 三、常用四種容器
# 1.list
l = [1, 'a', 2, 'b']
#修改
l[0] = 3
#增加
l.append(3)
#遍歷
for item in l:
print(item)
#索引遍歷
i = 0
while i != len(l):
print(l[i])
i += 1
#列表合併
print('合併(+): ', [1,2]+[3,4] )
#列表重複
print('重複(*): ', [1,2] * 5 )
#判斷元素是否存在列表中國
print('判斷是否存在(in): ', 1 in [1,2])
# 2.tuple
t = (1, 'a', 2, 'b')
#元組內容不能修改
#t(0) = 3
#遍歷
for item in t:
print(item)
#通過索引遍歷
i = 0
while i != len(t):
print(t[i])
i += 1
#解包 unpack
a, b, _, _ = t
print('unpack: ', c)
# 確保unpack接收的變量個數和tuple的長度相同,否則報錯
# 經常出現在函數返回值的賦值時
# a, b, c = t
# 3.dictionary
d = { '百度': 'https://www.baidu.com/',
'阿里巴巴': 'https://www.alibaba.com/',
'騰訊': 'https://www.tencent.com/'}
#遍歷key
for key in d.keys():
print(key)
#遍歷value
for value in d.values():
print(value)
#遍歷item
for key,value in d.items():
print('{}的網址是{}'.format(key,value))
# 4.set
print('創建set:')
my_set = {1, 2, 3}
print(my_set)
my_set = set([1, 2, 3, 2])
print(my_set)
print('添加單個元素:')
my_set.add(3)
print('添加3', my_set)
my_set.add(4)
print('添加4', my_set)
print('添加多個元素:')
my_set.update([4, 5, 6])
print(my_set)
# 四、Counter
import collections
c1 = collections.Counter(['a','b','c','a','b','b'])
c2 = collections.Counter({'a':2,'b':3,'c':1})
c3 = collections.Counter(a=2,b=3,c=1)
print(c1)
print(c2)
print(c3)
#更新
#注意這裏是做“加法”,不是“替換”
c1.update({'a':4,'b':-2,'c':4})
print(c1)
#訪問
print('a= ',c1['a'])
#對比 dict 的區別
print('e=', c1['e'])
#print('d=', d['d'])
# element()方法
for element in c1.elements():
print(element)
#most_common()方法
c1.most_common(3)
# 五、defaultdict
#應用場景1:統計每個字母出現的次數
s = 'hello python,hello world'
#三種方法比較
# 1 使用Counter
print(collections.Counter(s))
# 2 使用 dict
counter = {}
for c in s:
if c not in counter:
counter[c]=1
else:
counter[c] += 1
print(counter.items())
# 3 使用defaultdict
counter2 = collections.defaultdict(int)
for c in s:
counter2[c] += 1
print(counter2.items())
#應用場景2:記錄相同元素的列表
colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k,v in colors:
d[k].append(v)
#print(k)
#print(v)
#print(d[k])
print(d.items())
# 六、map() 函數
import math
l1 = [1, 3, 5, 7, 9]
l2 = [2, 4, 6, 8, 10]
mins = map(min, l1, l2)
print(mins)
# map()函數操作時,直到訪問數據時纔會執行
for item in mins:
print(item)
print('示例2,對列表中的元素進行平方根操作:')
squared = map(math.sqrt, l2)
print(squared)
print(list(squared))
# 七、匿名函數 lambda
my_func = lambda a, b, c: a * b
print(my_func)
print(my_func(1, 2, 3))
# 結合map
print('lambda結合map')
l1 = [1, 3, 5, 7, 9]
l2 = [2, 4, 6, 8, 10]
resault = map(lambda x, y: x * 2 + y, l1, l2)
print(resault)
print(list(resault))
# 八、Python操作CSV數據文件
import csv
with open('grades.csv') as csvfile:
grades_data = list(csv.DictReader(csvfile))
print('記錄個數:', len(grades_data))
print('前2條記錄:', grades_data[:2])
print('列名:', list(grades_data[0].keys()))
avg_assign1 = sum([float(row['assignment1_grade']) for row in grades_data]) / len(grades_data)
print('assignment1平均分數:', avg_assign1)
assign1_sub_month = set(row['assignment1_submission'][:7] for row in grades_data)
print(assign1_sub_month)