今天的內容主要介紹的是列表List、元組Tuple以及字典Dictionary和集合Set,學會這些東西將會對於資料整理、爬蟲、數據分析等等許多領域都會有很多幫助~
lst = [3,4,5]
print(lst)
print(lst[0])
print(lst[-1])
lst[2] = 'py'
print(lst)
lst.append('foo')
print(lst)
#[3, 4, 5]
#3
#5
#[3, 4, 'py']
#[3, 4, 'py', 'foo']
lst = list(range(5))
print(lst)
print(lst[2:4]) #不含4
print(lst[2:])
print(lst[:4])
print(lst[:])
print(lst[:-1])
lst[2:4] = [8,9]
print(lst)
#[0, 1, 2, 3, 4]
#[2, 3]
#[2, 3, 4]
#[0, 1, 2, 3]
#[0, 1, 2, 3, 4]
#[0, 1, 2, 3]
#[0, 1, 8, 9, 4]
ani = ['cat','dog','bird','elephant','lion']
for idx,item in enumerate(ani): #enumerate 清單
print(idx,item)
# 0 cat
# 1 dog
# 2 bird
# 3 elephant
# 4 lion
a = [x for x in range(10)]
print(a)
b = [y+1 for y in range(10)]
print(b)
c = [z for z in range(10) if z % 2 == 1]
print(c)
e = [x**2 for x in range(10) if x % 2 == 0]
print(e)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#[1, 3, 5, 7, 9]
#[0, 4, 16, 36, 64]
tp =(3,4,5,6)
print(type(tp)) #<class 'tuple'>
print(tp) #(3,4,5,6)
print(tp[0]) #3
print(tp[1]) #4
print(tp[-1]) #6
for ele in tp:
print(ele,end = " ") #3 4 5 6 #end = " " 附加一空格
#<class 'tuple'>
#(3, 4, 5, 6)
#3
#4
#6
#3 4 5 6
a = {'cat':'miao','dog':'wang'}
print(a['dog'])
print('dog' in a)
a['bird'] = 'juju'
print(a.get('eagle','N/A')) # 取出eagle 若無則印N/A
print(a.get('bird','N/A'))
del a['bird']
print(a.get('bird','N/A'))
#wang
#True
#N/A
#juju
#N/A
a = {'bird':2,'dog':4,'cat':4}
for idx,leg in a.items():
print('動物 %s 有 %d 隻腳' %(idx,leg))
#動物 bird 有 2 隻腳
#動物 dog 有 4 隻腳
#動物 cat 有 4 隻腳
dict = {x:x**2 for x in range(5)}
print(dict)
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict = {x:x**2 for x in range(10) \ # \ = 接續下一行
if x % 2 == 0}
print(dict)
#{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
s = {'dog','cat','bird'}
print('dog' in s)
print('monkey' in s)
s.add('monkey')
print('monkey' in s)
print(len(s))
s.add('dog')
print(len(s))
s.remove('dog')
print(len(s))
#True
#False
#True
#4
#4
#3
s = {'dog','cat','bird'}
for idx,ani in enumerate(s):
print('#%d:%s' %(idx+1,ani))
#1:cat
#2:dog
#3:bird
a = {1,2,3,4,5}
b = {4,5,6,7,8}
c = a & b
print(c)
d = a.intersection(b)
print(d) #交集 intersection() or &
e = a | b
print(e)
f = a.union(b)
print(f) #聯集 union() or |
g = a - b
print(g)
h = a.difference(b)
print(h) #差集 difference() or -
i = a ^ b
print(i)
j = a.symmetric_difference(b)
print(j) #對稱差集 symmetric_difference() or ^
#{4, 5}
#{4, 5}
#{1, 2, 3, 4, 5, 6, 7, 8}
#{1, 2, 3, 4, 5, 6, 7, 8}
#{1, 2, 3}
#{1, 2, 3}
#{1, 2, 3, 6, 7, 8}
#{1, 2, 3, 6, 7, 8}