練習1:猜年齡遊戲 java
要求:python
guess_age=24 count = 0 while count < 3: age = int(input("請輸入年齡")) if guess_age > age: print ("你猜小了") elif guess_age < age: print ("你猜大了") else: print("恭喜你回答正確") count += 1 else: print("遊戲結束")
練習2:猜年齡遊戲升級版 git
要求:編程
count = 0 age = 24 while True: guess_age = input('請輸入您猜想的年齡: ') if guess_age == age: print('恭喜你,猜對啦!') break else: print('猜錯啦,請從新輸入') count += 1 if count == 3: print('您是否想從新玩,回答Y/y或者N/n') ans = input('請輸入您心裏的想法: ') if ans == 'Y' or ans == 'y': print('請繼續您的遊戲吧!') elif ans == 'N' or ans == 'n': print('謝謝您參與遊戲!') break
解釋型:「同聲翻譯」,一邊翻譯成目標代碼即機器語言一邊執行,運行效率比較低且不能生成可獨立執行的可執行文件,應用程序不能脫離解釋器,這種方式比較靈活,能夠動態調整、修改應用程序。能夠跨平臺,開發效率高。如:java、python等app
id
(變量名)
#查看內存地址。
_username = "seven"
_passworld = "123" username = input("username:") passworld = input("passworld:") if username == _username and passworld == _passworld: print("登陸成功")
_username = "seven"
_passworld = "123" count = 0 while count < 3: username = input("username:") passworld = input("passworld:") if username == _username and passworld == _passworld: print("登陸成功") break else: print("登陸失敗,請從新輸入") count += 1
#_username = ["seven" , "alex"] #運用列表
_username = "seven" or "alex"
_passworld = "123"
count = 0
while count < 3:
username = input("username:")
passworld = input("passworld:")
if username == "seven" or "alex" and passworld == _passworld:
#if username in _username and passworld == _passworld: #判斷
print("登陸成功")
break
else:
print("登陸失敗,請從新輸入")
count += 1
寫代碼iphone
a. 使用while循環實現輸出2-3+4-5+6...+100 的和 oop
i = 2
total_1 = 0 total_2 = 0 while i <=100: if i%2 == 0: total_1 += i else: total_2 += -i i += 1 total = total_1 + total_2 print(total)
b. 使用 while 循環實現輸出 1,2,3,4,5, 7,8,9, 11,12性能
count = 1
while count <= 12:
if count == 10 or count==6: pass else: print("loop",count) count +=1
c. 使用while 循環輸出100-50,從大到小,如100,99,98...,到50時再從0循環輸出到50,而後結束 spa
i = 101
while i >= 51:
i -=1 print(i) i = 0 while i <= 50: print(i) i +=1
d. 使用 while 循環實現輸出 1-100 內的全部奇數 翻譯
i = 1
while i <= 100:
if i %2==1: print(i) i+=1
e. 使用 while 循環實現輸出 1-100 內的全部偶數
i = 0
while i <= 100:
if i %2==0: print(i) i+=1
現有以下兩個變量,請簡述 n1 和 n2 是什麼關係?
n1 = 123456 n2 = n1 關係是給數據
123456
起了另一個別名n2,至關於n1和n2都指向該數據的內存地址
給數據123456起了另一個別名n2,至關於n1和n2都指向該數據的內存地址
製做趣味模板程序(編程題)
需求:等待用戶輸入名字、地點、愛好,根據用戶的名字和愛好進行任意顯示
如:敬愛可愛的xxx,最喜歡在xxx地方幹xxx
username = input("name:")
place = input("place:") love = input("love:") info = ''' 敬愛的%s最喜歡在 %s幹 %s '''% (username,place,love) print(info)
輸入一年份,判斷該年份是不是閏年並輸出結果。(編程題)
注:凡符合下面兩個條件之一的年份是閏年。 (1) 能被4整除但不能被100整除。 (2) 能被400整除。
year = int(input("please input a year:"))
if (year %2==0 and year %100!=0) or (year %400==0): print(year,"是閏年") else: print(year,"不是閏年")
假設一年期按期利率爲3.25%,計算一下須要過多少年,一萬元的一年按期存款連本帶息能翻番?(編程題)
money = 10000
year = 0
while money <= 20000: year +=1 money = money * (1+0.0325) print(year,money) print(year,"年之後,一萬元的一年按期存款連本帶息能翻番")
打印索引值:
#10 打印每一個索引值和元素
names = ['alex','jack','rain','mack','racheal','shanshan']
count = 0
for i in names:
print(count,i)
count += 1
for i in enumerate(names):#枚舉
print(i)
for index,i in enumerate(names):#枚舉
print(index,i)
#輸出
0 alex
1 jack
2 rain
3 mack
4 racheal
5 shanshan
(0, 'alex')
(1, 'jack')
(2, 'rain')
(3, 'mack')
(4, 'racheal')
(5, 'shanshan')
0 alex
1 jack
2 rain
3 mack
4 racheal
5 shanshan
#11題 names = ['alex','jack','rain','mack','racheal','shanshan'] for index,i in enumerate(names):#枚舉 if index%2 ==0: #偶數 names[index] = -1 print(index,i) print(names)
#12題 names = ['alex','jack','peiqi',2,'rain','mack',2,'racheal','shanshan',2,'longting'] first_index = names.index(2) new_list = names[first_index+1:] second_index = new_list.index(2) second_val = names[first_index + second_index +1] print(new_list,first_index,second_index) print('second values:',second_val)
#13 products = [['iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]] print('-------------商品列表--------------') for index,i in enumerate(products):#枚舉 print("%s.%s %s" %(index,i[0],i[1]) )
#14 products = [['iphone8',6888],['MacPro',14800],['小米6',2499],['Coffee',31],['Book',80],['Nike Shoes',799]] shopping_cart = [] run_flag = True #標誌位 while run_flag: #exit_flag = False #while not exit_flag: #while True: print('-------------商品列表--------------') for index,i in enumerate(products):#枚舉 print("%s.%s %s" %(index,i[0],i[1]) ) choice = (input("輸入你想買的商品編號或者輸入q退出:")) if choice.isdigit(): choice = int(choice) if choice >=0 and choice <= len(products): shopping_cart.append(products[choice]) print("Added product %s into shopping cart."%(products[choice])) else: print("此商品不存在") elif choice == 'q': if len(shopping_cart) > 0: print("----------您已購買如下商品-------") for index,i in enumerate (shopping_cart): print("%s.%s %s" % (index,i[0],i[1])) run_flag =False #exit_flag = True #break
寫代碼,有以下字典,按照要求實現每個功能。dic = {'k1':'v1','k2':'v2','k3':'v3'}
1.請循環遍歷出全部的key
for k in dic: print(k)
2請循環遍歷出全部的value
for k in dic: print(dic[k])
3請循環遍歷初全部的KEY和VALUE
for k in dic: print(k,dic[k])
4請在字典中添加一個鍵值對,'k4':'v4',輸出添加後的字典
dic['k4'] = 'v4' print(dic)
5請刪除字典中鍵值對'k1','v1',並輸出刪除後的字典
dic.pop('k1') print(dic)
6請刪除字典中鍵'k5'對應的鍵值對,若是字典中不存在鍵'k5',則不報錯,而且讓其返回none
if 'k5' in dic: dic.pop('k5') else: print(dic.get('k5'))
7請獲取字典中'k2'對應的值
print(dic.get('k2'))
8請獲取字典中'k6'對應的值,若是'k6'不存在,則不報錯,而且讓其返回Nnoe
print(dic.get('k6'))
9現有dic2 = {'k1':'v111','a':'b'}請經過一行操做使dic2 = {'k1':'v1','k2':'v2','k3':'v3','a':'b'}
dic = {'k1':'v1','k2':'v2','k3':'v3'} dic2 = {'k1':'v111','a':'b'} dic2.update(dic) print(dic2)
10.組合嵌套題,寫代碼,有以下列表,按照要求實現每個功能 lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']]
10.1.將列表lis 中的'tt'變成大寫(用兩種方式)
#方法1 print(lis[0][1][2].get('k1')[0].upper()) #方法2 print(lis[0][1][2].get('k1')[0].swapcase())
10.2.將列表中的數字3 變成字符串'100'(用兩種方式)
#方法1 print(lis) lis[0][1][2].get('k1')[1] = '100' print(lis) #方法2 lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']] dic3 = {'k1':['tt','100','1']} print(lis) lis[0][1][2].update(dic3) print(lis)
10.3 將列表中的字符串'1'變成數字101(用兩種方式)
#方法1 lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']] print(lis) lis[0][1][2].get('k1')[2] = 101 print(lis) #方法2 lis = [['k',['qwe',20,{'k1':['tt',3,'1']},89],'ab']] dic3 = {'k1':['tt',3,101]} print(lis) lis[0][1][2].update(dic3) print(lis)
11 按照要求實現如下功能:
現有一個列表li = [1,2,3,'a','b',4,'c'],有一個字典(此字典是動態生成的,你並不知道他裏賣弄有多少鍵值對,因此
用dic = {}模擬此字典);如今須要完成這樣的操做:若是該字典沒有'k1'這個鍵,那就建立'k1'鍵和其對應的值(該鍵對應的值設置爲空列表)
並將列表li 中的 索引爲奇數的對應元素,添加到'k1'這個鍵對應的空列表中。若是該字典有'k1'這個鍵,且'k1'對應的value
是列表類型,那就將li中的索引爲奇數的對應元素,添加到'k1'這個鍵對應的鍵中
dic = {'k2':2,'k3':3}#1. dic{}字典中 沒有 'k1' #dic = {'k1':['we','tt'],'k2':2}#2 dic{}字典中有'k1' #dic = {'k1':1,'k2':33} # 有'k1'但'k1'value 非列表 li = [1,2,3,'a','b',4,'c'] if not 'k1' in dic: dic.setdefault('k1',[]) for i in li : if li.index(i) % 2 == 1: dic['k1'].append(i) else: if type(dic['k1']) == type([]): for i in li: if li.index(i) % 2 == 1: dic['k1'].append(i) else: print("字典K1,VALUE 不是列表,沒法追加") print(dic)
一、請用代碼實現:利用下劃線將列表的每個元素拼接成字符串,li=['alex', 'eric', 'rain']
>>> li = ['alex','eric','rain']
>>> '_'.join(li) 'alex_eric_rain'
二、查找列表中元素,移除每一個元素的空格,並查找以a或A開頭而且以c結尾的全部元素。
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain")
dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain") dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"} list1 = list(tu) list2 = list(dic.values()) new_list = li + list1 + list2 for i in new_list: ret = i.strip() # i.strip():刪除字符串當前行首尾的的空格 if (ret.startswith('a') or ret.startswith('A') or ret.endswith('c')): #startswith查看是否已什麼開始,endswith查看是否已什麼結尾 print(ret)
三、寫代碼,有以下列表,按照要求實現每個功能
li=['alex', 'eric', 'rain']
a
>>> li = ['alex','eric','rain']
>>> v = len(li) >>> v 3
b
>>> li.append('seven')
>>> li ['alex', 'eric', 'rain', 'seven']
c
>>> li.insert(0,'Tony')
>>> li ['Tony', 'alex', 'eric', 'rain', 'seven']
d
>>> li[1] = 'Kelly'
>>> li
['Tony', 'Kelly', 'eric', 'rain', 'seven']
e
>>> li.remove('eric')
>>> li ['Tony', 'Kelly', 'rain', 'seven']
f
>>> del li[1]
> K = del.li[1]
>>> li ['Tony', 'rain', 'seven']
g
>>> del li[2]
>>> li ['Tony', 'rain']
h
>>> del li[1:3]
>>> li ['Tony']
i
>>> li = ['alex','eric','rain']
>>> li ['alex', 'eric', 'rain'] >>> li.reverse() >>> li ['rain', 'eric', 'alex']
j
li = ['alex','eric','rain']
for i in range(len(li)): print(i)
k
li = ['alex','eric','rain']
for k ,v in enumerate(li,100): print(k,v)
l
li = ['alex','eric','rain']
for i in li : print(i)
四、寫代碼,有以下列表,請按照功能要求實現每個功能
li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123, 446]
li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123, 446]
print(li[2][1][1])
li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123, 446]
li[2][2] = 'All' print(li)
五、寫代碼,有以下元組,請按照功能要求實現每個功能
tu=('alex', 'eric', 'rain')
>>> tu = ('alex','eric','rain') >>> len(tu) 3
>>> tu ('alex', 'eric', 'rain') >>> tu[1] 'eric'
>>> tu ('alex', 'eric', 'rain') >>> tu[0:2] ('alex', 'eric')
tu = ('alex', 'eric', 'rain') for i in tu: print(i)
tu = ('alex','eric','rain') for i in range(len(tu)): print(i)
tu = ('alex','eric','rain') for k,v in enumerate(tu,10): print(k,v)
六、有以下變量,請實現要求的功能
tu = ("alex", [11, 22, {"k1": 'v1', "k2": ["age", "name"], "k3": (11,22,33)}, 44])
a 特性: 1.可存放多個值; 2.不可變; 3.按照從左到右的順序定義元組元素,下標從0開始順序訪問,有序
b 不可被修改。
c k2對應的值是列表,能夠被修改。
>>> tu ('alex', [11, 22, {'k1': 'v1', 'k2': ['age', 'name'], 'k3': (11, 22, 33)}, 44]) >>> tu[1][2]['k2'].append('seven') >>> tu ('alex', [11, 22, {'k1': 'v1', 'k2': ['age', 'name', 'seven'], 'k3': (11, 22, 33)}, 44])
d k3對應的是元組,不能被修改。
七、字典
dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}
a
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]} for k in dic: print(k)
b
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]}
for k in dic.values():
print(k)
# for k in dic:
# print(dic[k])
c
dic = {'k1':'v1','k2':'v2','k3':[11,22,33]} for k,v in dic.items(): #items 是把字典轉換成列表 print(k,v) # for k in dic: # print(k,dic[k])
e
>>> dic {'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33]} >>> dic['k4'] = 'v4' >>> dic {'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33], 'k4': 'v4'}
f
{'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33], 'k4': 'v4'} >>> dic['k1'] = 'alex' >>> dic {'k1': 'alex', 'k2': 'v2', 'k3': [11, 22, 33], 'k4': 'v4'}
g
>>> dic['k3'].append(44) >>> dic {'k1': 'alex', 'k2': 'v2', 'k3': [11, 22, 33, 44], 'k4': 'v4'}
k
>>> dic {'k1': 'alex', 'k2': 'v2', 'k3': [11, 22, 33, 44], 'k4': 'v4'} >>> dic['k3'].insert(0,18) >>> dic {'k1': 'alex', 'k2': 'v2', 'k3': [18, 11, 22, 33, 44], 'k4': 'v4'}
八、轉換
>>> s = "alex" >>> list(s) ['a', 'l', 'e', 'x']
>>> tuple(s) ('a', 'l', 'e', 'x')
>>> li = ["alex","seven"] >>> tuple(li) ('alex', 'seven')
>>> tu = ('Alex','seven') >>> list(tu) ['Alex', 'seven']
li = ["alex","seven"] dic ={} for k ,v in enumerate (li,10): dic[k] = v #列表轉換成字典 print(dic)
九、元素分類
有以下值集合[11,22,33,44,55,66,77,88,99,90],將全部大於66的值保存至字典的第一個key中,將小於66的值保存至第二個key的值中。
即:{'k1':大於66的全部值, 'k2':小於66的全部值}
li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90] li.sort() #排序 z = li.index(66) l = len(li) dict = {'k1':li[z+1:l],'k2':li[:z]} print(dict)
十、輸出商品列表,用戶輸入序號,顯示用戶選中的商品
商品li = ["手機", "電腦", '鼠標墊', '遊艇']
li = ["手機", "電腦", '鼠標墊', '遊艇'] for k,i in enumerate(li): print(k,i) num = int(input("please input your number:")) print(li[int(num)]) choice = input('是否添加商品(y|Y):') if choice == 'y' or choice == 'Y': goods = input("請輸入商品:") li.append(goods) #添加商品 for k,i in enumerate(li): print(k, i) s = input("是否查找商品(y|Y):") if s == 'y' or s == 'Y' : n = int(input('請輸入要查詢的序號:')) print(li[n])
十一、用戶交互顯示相似省市縣N級聯動的選擇
city = {"北京":{"朝陽":["大望路","國貿"], "昌平":["沙河","昌平"]}, "河北":{"張家口":["沙城","宣化"], "石家莊":["某某路","某某街"]} } go = True while go: cc = [] dq = [] print("\33[31;1m一級列表\33[1m".center(40,"=")) for i,v in enumerate(city,1): print(i,v) cc.append(v) print("\33[35;1m插入數據 i 退出按Q\33[1m") u_c1 = str(input(">>>")) if u_c1.isdigit():#進二級以前判斷 u_c1 = int(u_c1) if u_c1 >0 and u_c1 <=len(cc): while go: print("\33[32;1m二級列表\33[1m".center(40, "=")) for i1,v1 in enumerate(city[cc[u_c1-1]],1): print(i1,v1) dq.append(v1) print("\33[35;1m退出按Q 返回 B\33[1m") u_c2 = input(">>>") if u_c2.isdigit():#進三級以前判斷 u_c2 = int(u_c2) if u_c2 >0 and u_c2<=len(dq): while go: print("\33[32;1m三級列表\33[1m".center(40, "=")) for s in city[cc[u_c1-1]][dq[u_c2-1]]: print(s) print("\33[35;1m退出按Q 返回 B\33[1m") u_c3 = input(">>>") if u_c3 == "q" or u_c3 == "Q": go = False break if u_c3 == "b" or u_c3 =="B": del dq[:] break else: print("\33[31;1m輸入不正確\33[1m") else: print("\33[31;1m輸入超出範圍!\33[1m") elif u_c2 == "q" or u_c2 == "Q": go = False break elif u_c2 == "b" or u_c2 == "B": del cc[:] del dq[:] break else: print("\33[31;1m輸入格式不對!\33[1m") elif u_c1.isalpha(): if u_c1 == "q" or u_c1 == "Q": break elif u_c1 == "i" or u_c1 == "I": print("\33[32;1m添加信息\33[1m".center(40,"=")) ct_name = input("省:") if ct_name == "Q" or ct_name == "q": break else: if city.get(ct_name,0) == 0: city[ct_name] = {} dq_name = input("市:") if dq_name == "Q" or dq_name == "q": break else: if city[ct_name].get(dq_name,0) == 0: city[ct_name][dq_name]=[] while True: print("\33[31;1m循環添加,退出請按Q!\33[1m") s = input("縣:") if s == "q" or s == "Q": break else: city[ct_name][dq_name].append(s) else: print("\33[31;1m輸入超出範圍!\33[1m") else: print("\33[31;1m輸入格式不對!\33[1m")
十二、列舉布爾值是False的全部值
1 None "" () [] {} 0
1三、有兩個列表
l1 = [11,22,33]
l2 = [22,33,44]
l1 = [11,22,33]
l2 = [22,33,44]
print(list(set(l1) & set(l2)))
print(list(set(l1) - set(l2)))
print(list(set(l2) - set(l1)))
print(list(set(l2) ^ set(l1)))
1四、利用For循環和range輸出
for i in range(100,0,-1): print(i) for i in range(1,101): print(i) while True: a = 100 for i in range(100): print(a - i) break while True: for i in range(100): print(i+1) break
1五、利用for循環和range輸出9 * 9乘法表
#方法一 for x in range(1,10): for y in range(1,x+1): print("{0} * {1} = {2}".format(x,y,x*y),end = " ") #end = " " 做用就是:不換行 print('\n',end = " ") #方法二: for i in range(1,10): for j in range(1,i+1): print("%d*%d=%2d" % (i,j,i*j),end=" ") #%d是數值整型對應的格式通配符 print(" ")
1六、求100之內的素數和。(編程題)
解題思路:
#1
L=[]
for i in range(2,101):
flg=True
for j in range(2,i):
if (i%j==0):
flg=False
break
if flg:
L.append(i)
print(L)
#2
for i in range(2,101):
fg = 0
for j in range(2,i-1):
if i%j == 0:
fg = 1
break
if fg == 0:
print i
1七、將[1,3,2,7,6,23,41,24,33,85,56]從小到大排序(冒泡法)(編程)
li = [1,3,2,7,6,23,41,24,33,85,56] for i in range(len(li)-1): # i的範圍0-9 if li[i] > li[i+1]: # 相鄰的兩個數比較 li[i],li[i+1] = li[i+1],li[i] print(li)
1八、分頁顯示內容
a.經過for循環建立301條數據,數據類型不限,如:
alex-‐1alex1@live.compwd1
alex-‐2alex2@live.compwd2
alex-‐3alex3@live.compwd3
....
1 for i in range(301): 2 a = "alex- - %salex%s@live.com pwd%s"%(i+1,i+1,i+1) 3 print(a)
b.提示用戶請輸入要查看的頁碼,當用戶輸入指定頁碼,則顯示指定數據
注意:
-‐每頁顯示10條數據
-‐用戶輸入頁碼是非十進制數字,則提示輸入內容格式錯誤
while True: u = [] for i in range(301): a = "alex{0} alex{0}@live.com pwd{0}".format(i+1) x = [a] u = u + x # print(u[0:10]) s = input("請輸入您想查看的頁碼:") v3 = s.isnumeric() #檢測字符串是否只由數字組成,若是字符串中只包含數字字符,則返回 True,不然返回 False if v3 == False : print("輸入內容格式錯誤") elif int(s) < 1 or int(s) > 31: print("輸入頁碼錯誤") else: s = int(s) a = (s-1)*10 b = s*10 j = (u[a:b]) for g in j: print(g) A =input("是否繼續查看(y or Y)") if A =="y" or A =="Y": continue else: break
1九、有一、二、三、四、五、六、七、八、8個數字,能組成多少個互不相同且無重複數字的3位數?
count = 0 for i in range(1, 9): for x in range(1, 9): for y in range(1, 9): if i != x and x != y and i != y: print(i, x, y) count += 1 print(count)
20、有一下列表,
nums=[2,7,11,15,1,8,7]
請找到列表中任意兩個元素相加可以等於9的元素集合,如:[(0,1),(4,5)]
nums = [2, 7, 11, 15, 1, 8, 7] li = [] n1 = [] for i in nums: for x in nums: y = i + x if y == 9: v = [i, x] x =(i,x) if v not in li: v.reverse() if v not in li: n1.append(x) li.append(v) print(n1)
2一、用Python開發程序自動計算方案:
公雞5文錢一隻,母雞3文錢一隻,小雞3只一文錢,用100文錢買100只雞,其中公雞,母雞,小雞都必需要有,問公雞,母雞,小雞要買多少隻恰好湊足100文錢?
for x in range(1, 100): for y in range(1, 100): for z in range(1, 100): if x + y + z == 100 and 5 * x + 3 * y + z / 3 == 100: # 小雞 1/3 print(x, y, z)
執行結果:
1 4 18 78 2 8 11 81 3 12 4 84
分別用append、extend方法,給一個序列增長一個元素
>>> lst1 = [4,2,'rs','name'] >>> lst1.append(9) >>> print(lst1) [4, 2, 'rs', 'name', 9] >>> lst1.extend([1,2,3]) >>> print(lst1) [4, 2, 'rs', 'name', 9, 1, 2, 3]
x.append([1,2,3])和x.extend([1,2,3])的區別
x.append('abc')和x.extend('abc')的區別
>>> lst1.append([1,2,3]) >>> print(lst1) [4, 2, 'rs', 'name', 9, 1, 2, 3, [1, 2, 3]] >>> lst1.extend([1,2,3]) >>> print(lst1) [4, 2, 'rs', 'name', 9, 1, 2, 3, [1, 2, 3], 1, 2, 3] >>> lst1.append('abc') >>> print(lst1) [4, 2, 'rs', 'name', 9, 1, 2, 3, [1, 2, 3], 1, 2, 3, 'abc'] >>> lst1.extend('abc') >>> print(lst1) [4, 2, 'rs', 'name', 9, 1, 2, 3, [1, 2, 3], 1, 2, 3, 'abc', 'a', 'b', 'c'] >>>
sort()和sorted()什麼區別
>>> lst1.sort() >>> print(lst1) [2, 4, 5, 8, 9] >>> lst1.sort(reverse=True) >>> print(lst1) [9, 8, 5, 4, 2] >>> lst2 = sorted(lst1) >>> print(lst2) [2, 4, 5, 8, 9] >>>
m=[4,5,6,73,4,4,4,4,2],刪除全部的4
#方法一 set()方法 >>> m [4, 5, 6, 73, 4, 4, 4, 4, 2] >>> list(set(m)) [2, 4, 5, 6, 73] #方法二 set() 方法會改變列表順序,使用sort()使之與原來的相同; >>> z = list(set(m)) >>> z.sort(key = m.index) >>> z [4, 5, 6, 73, 2] #方法三 >>> m=[4,5,6,73,4,4,4,4,2] >>> n={}.fromkeys(m).keys() #fromkeys()用於建立一個字典; >>> n dict_keys([4, 5, 6, 73, 2]) #方法四: m=[4,5,6,73,4,4,4,4,2] n=[] for i in m: if i not in n: n.append(i) print(n) 打印: [4, 5, 6, 73, 2]dict.fromkeys(iterable[,value=None])