1.已知串列li_num1 = [4, 5, 2, 7]和li_num2 = [3, 6],請將這兩個串列合并為一個串列,并將合并后的串列中的元素按降序排列,
1 # 方法一 2 li_num1 = [4, 5, 2, 7, ] 3 li_num2 = [3, 6] 4 # extend() 函式用于在串列末尾一次性追加另一個序列中的多個值(用新串列擴展原來的串列), 5 li_num1.extend(li_num2) # 通過extend()函式在li_num1末尾插入li_num2串列, 6 li_num1.sort() # 通過sort()函式將li_num1串列中的元素進行排序,由于未給引數即為升序排序 7 print(li_num1.reverse()) 8 print(li_num1) 9 10 # 方法二 11 li_num1 = [4, 5, 2, 7] 12 li_num2 = [3, 6] 13 li_num = li_num1 + li_num2 14 li_num.sort() 15 li_num.reverse() 16 print(li_num)
輸出結果:
[7, 6, 5, 4, 3, 2]
2.已知元組tu_num1 = (”p”, ”y”, ”t”, [”o”, ”n”]),請向元組的最后一個串列中添加新元素“h”,
# ① num = ("p", "y", "t", ["o", "n"]) num[3].insert(1, "h") print(num) # ② tu_num1 = ("p", "y", "t", ["o", "n"]) tu_num1[-1].append('h') print(tu_num1) 輸出結果: ('p', 'y', 't', ['o', 'h', 'n']) ('p', 'y', 't', ['o', 'n', 'h'])
3.已知字串str= ”skdaskerkjsalkj”,請統計該字串中各字母出現的次數,
# ① syr = 'skdaskerkjsalkj' dic = dict() for x in syr: dic[x] = syr.count(x) print(dic) 輸出結果: {'s': 3, 'k': 4, 'd': 1, 'a': 2, 'e': 1, 'r': 1, 'j': 2, 'l': 1} # ② str = "skdaskerkjsalkj" c_dict = {} # 定義一個串列用來存盤統計的結果 strset = set(list(str)) # 集合中不會出現重復資料 for each in strset: times = str.count(each) # 得到each在str中出現的數量 c_dict[each] = times print(c_dict) 輸出結果: {'k': 4, 'a': 2, 'l': 1, 'd': 1, 's': 3, 'r': 1, 'e': 1, 'j': 2} # ③ str1 = 'skdaskerkjsalkj' x = list(str) for i in x: print(i, '出現的次數:', x.count(i)) x.remove(i) # 洗掉查詢后的字符 輸出結果: s 出現的次數: 3 d 出現的次數: 1 s 出現的次數: 2 e 出現的次數: 1 k 出現的次數: 4 s 出現的次數: 1 l 出現的次數: 1 j 出現的次數: 2
4、已知串列li_one = [1,2,1,2,3,5,4,3,5,7,4,7,8],撰寫程式實作洗掉串列li_one中重復資料的功能,
li_one = [1, 2, 1, 2, 3, 5, 4, 3, 5, 7, 4, 7, 8] d = dict() for i in li_one: if i in d.keys(): d[i] = d[i] + 1 else: d[i] = 1 for i, k in d.items(): if k > 1: li_one.remove(i) print(li_one) 輸出結果: [1, 2, 3, 5, 4, 7, 8]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/543010.html
標籤:其他
上一篇:netty對多協議進行編解碼
