TQC-第七大類-Tuple、Set、Dictionary其他容器

這篇文章教你輕鬆學習Python的資料結構:`tuple`像串列,`set`不重複元素,`dictionary`鍵值對存儲。還介紹排序技巧和合併字典的方法,用於處理各種專業資料操作需求,簡直是編程小白的宝典!趕緊上手,讓編程變得如此有趣!

以下大方向請先熟悉:

Tuple元組

轉型成tuple

1
tuple(物件)

Set集合

不會加入重複的內容的容器

創建set

1
s=set()

新增元素

1
s.add(元素)

Dictionary字典

創建字典

1
d={}

加入字典

1
d[key]=value

合併字典

1
d1.update(d2)#將d2合併至d1

Python內建函數

排序:sorted

1
sorted(可排序物件)

702 tuple操作

把它當作串列即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
print('Create tuple1:')
tuple1,tuple2=[],[]
while True:
n=int(input())
if n==-9999:
break
else:
tuple1.append(n)

print('Create tuple2:')
while True:
n=int(input())
if n==-9999:
break
else:
tuple2.append(n)

print('Combined tuple before sorting:',tuple(tuple1+tuple2))
print('Combined list after sorting:',sorted(tuple1+tuple2))

704set集合

會創建set和新增元素即可

1
2
3
4
5
6
7
8
9
10
11
n=set()
while True:
num=int(input())
if num==-9999:
break
else:
n.add(num)
print('Length:',len(n))
print('Max:',max(n))
print('Min:',min(n))
print('Sum:',sum(n))

706全字母

先將文字轉換成小寫,檢定的測資一定有「空白鍵」,所以只要計算長度是不是27就可以了(a~z 26個字母 加上 空格)

1
2
3
4
5
6
7
n=int(input())
for i in range(n):
s=set(input().lower())
if len(s)==27:
print('True')
else:
print('False')

708字典的合併與排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
d1 = {}
d2 = {}
print('Create dict1:')
while True:
n = input('Key: ')
if n == 'end':
break
k = input('Value: ')
d1[n] = k
print('Create dict2:')
while True:
n = input('Key: ')
if n == 'end':
break
k = input('Value: ')
d2[n] = k
d1.update(d2)
ks = sorted(d1)
# print(ks)
forin ks:
print(f'{值}: {d1[值]}')

710 字典內容存在

1
2
3
4
5
6
7
8
9
10
11
12
13
14
d = {}
while True:
key=input('Key: ' )
if key=='end':
break
value=input('Value: ')
d[key]=value
# print(d)
# print(d['123-555'])
s=input('Search key: ')
if s in d:
print(True)
else:
print(False)

TQC-第七大類-Tuple、Set、Dictionary其他容器
https://codinglu.tw/2025/05/tqc-category-vii-tuple-set-dictionary-other-containers-python-certification/
作者
阿盧
發布於
2025年5月6日
許可協議
📌 本文瀏覽量: 0