7個關于Python的經(jīng)典基礎案例
更新時間:2021年11月06日 09:45:15 作者:小小程序員ol
這篇文章主要給大家分享 7個關于Python的經(jīng)典基礎案例,列表排序、調換字典鍵值、刪除列表中的重復元素、輸出質數(shù)、判斷是一年中第幾天、猜數(shù)字、進制轉換;,需要的朋友可以參考一下
1.列表排序
def que6():
# 6.輸入三個整數(shù)x, y, z,形成一個列表,請把這n個數(shù)由小到大輸出。
# 程序分析:列表有sort方法,所以把他們組成列表即可。
li = np.random.randint(-100, 100, size=10)
# 就地轉化
li = li.tolist()
# 用sort()結果
li_sort = sorted(li, reverse = False)
print('用sort方法,重新排列結果:{}'.format(li_sort))
# 不用sort方法,自己寫排序方法做,
# 冒泡排序
def bubbleSort(m):
m = m.copy()
for time in range(1, len(m)):
for index in range(len(m) - time):
if m[index] > m[index+1]:
m[index], m[index+1] = m[index+1] , m[index]
return m
# 選擇排序
def selectSort(m):
m = m.copy()
for seat_L in range(len(m)-1):
for seat_R in range(seat_L+1, len(m)):
if m[seat_L] > m[seat_R]:
m[seat_L], m[seat_R] = m[seat_R], m[seat_L]
return m
# 插入排序1(內部寫成函數(shù)):
def insertSort_1(m):
result = []
# 單個元素k插入列表li
def to_insert(li, k):
# 標識符
tab = False
# 尋找插入位置
# 循環(huán)次數(shù)應該至少大于列表長度+1,None也占一位(空列表),即認為撲克牌最末尾還有一張‘空牌'
for i in range(len(li) + 1):
# 修改標識符,標志‘遍歷完后的下一個循環(huán)',即在和‘空牌'比較
if i == (len(li)):
tab = True
# 如果在對li[-1]比較完成(包含)之前,且尋找到位置,即把撲克從左往右比較一遍
if not tab and k < li[i]:
li.insert(i, k)
break
# 如果遍歷完成,多循環(huán)一次,即和‘空牌'不需要比較,直接把牌替換掉‘空牌'
if tab:
li.append(k)
return li
# 遍歷列表
# result = result[:1]
for length in range(len(m)):
result = to_insert(result, m[length])
# print(result,m[length])
return result
# 插入排序2(直接嵌套循環(huán)):
def insertSort2(m):
m = m.copy()
result = m[:1]
for index_choose in range(1, len(m)):
# 手上已經(jīng)有index_choose張牌,比較第index_choose+1張牌則append
# 逐個比對手上的牌,如果都對比了一遍,則加到最后
for index_insert in range(len(result) + 1):
print(result, index_insert,'\n',m, index_choose,'\n\n')
if index_insert != index_choose and m[index_choose] < result[index_insert] :
result.insert(index_insert, m[index_choose])
break
if index_insert == index_choose:
result.append(m[index_choose])
# print(result, m[index_choose])
return result
# print(li)
print('插入排序:',insertSort3(li))
print('選擇排序:',selectSort(li))
print('冒泡排序:',bubbleSort(li))
que6()
2.調換字典鍵值
# 1. 調換元素.\
def que1():
d={1:"one",2:"two"}
# 方法1 --- 動態(tài)賦值
def method1(d):
d = d.copy()
result = {}
for k,v in d.items():
result[v] = k
return result
# 方法2 --- 生成器
def method2(d):
d = d.copy()
result = {v:k for k,v in d.items()}
return result
# 方法3 --- 由值尋找鍵
def method3(d):
d = d.copy()
# 由鍵尋找值
def match(dic, b):
return [k for k,v in dic.items() if v == b]
# 先生成key-None,再賦值
result = {}
result = result.fromkeys(d.values())
for k in result.keys():
result[k] = match(d, k)[0]
return result
# 方法4 --- 列表轉字典 < 直接轉換/動態(tài)賦值 >
def method4(d):
d = d.copy()
key = d.keys()
val = d.values()
data = list(zip(key, val))
# 方法4-1
result1 = {}
for i in range(len(data)):
result1[data[i][1]] = data[i][0]
# 方法4-2
result2 = dict(zip(val, key))
return result1, result2
print('新列表動態(tài)賦值方法:{}'.format(method1(d)))
print('生成器方法:{}'.format(method2(d)))
print('由鍵尋值方法:{}'.format(method3(d)))
print('動態(tài)賦值列表轉字典方法:{}'.format(method4(d)[0]))
print('直接列表轉字典方法:{}'.format(method4(d)[1]))
# que1()
3.刪除列表中的重復元素
遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流群:531509025
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
刪除重復元素list =[1,2,5,4,1,5,6,8,0,2,5]
a = np.random.randint(-100, 100, size=10)
a = a.tolist()
def method1(a):
a = a.copy()
a = set(a)
return a
def method2(a):
b = a.copy()
c = 0
for i in range(len(a)-1):
if b[i+c] in b[:i+c]+b[i+c+1:]:
b.pop(i+c)
c -= 1
return b
print('集合法:',method1(a))
print('遍歷法:',method2(a))
4.輸出質數(shù)
def prime(end):
prime_list = []
if end <= 1:
print('必須大于1')
else:
# prime_list.append(2)
for i in range(2, end+1, 1):
count = 0
if i == 2:
if i%2 != 0:
prime_list.append(2)
else:
for m in range(2, i):
# 能夠整除,則跳出循環(huán)
if (i % m) == 0:
# print(i, m)
break
# 否則計數(shù)+1
else:
count += 1
# 判斷是否整除完成(0/n)
if count == i - 2:
prime_list.append(i)
print(count, i, m)
return (prime_list)
num = int(input('想輸出2到多少?'))
print(prime(num))
5.判斷是一年中第幾天
def que3():
# 3.輸入某年某月某日,判斷這一天是這一年的第幾天?:
# 閏年判斷函數(shù)
def judge_leap(num):
date = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# (四年一閏 and not百年) or 四百年閏
if (num % 4 == 0 and num % 100 != 0) or num % 400 ==0:
date[1] =29
return date
# 格式轉換
date = (input('請輸入一個日期,格式如:“2018.02.12”:'))
date_list = (list(map(int, (date.split('.')))))
# 遍歷計算天數(shù)
day = date_list[2]
for i in range(date_list[1]):
day += judge_leap(date_list[0])[i]
print('{}月{}日是{}年的第{}天\n'.format(date_list[1], date_list[2], date_list[0], day))
# que3()
6.猜數(shù)字
# 重新猜數(shù)字
import random
def judge_num(num, num_random):
if num > num_random:
print('It\'s too big')
return 1
elif num < num_random:
print('It\'s too small')
return 1
else:
print("Congratulation!! That\' right!")
return 0
# 產生隨機數(shù)
num_start = int(input('Digital lower limit of guess number:\n'))
num_end = int(input('Digital upper limit of guess number:\n'))
num_random = random.randint(num_start, num_end)
# 參數(shù)初始化
result = 1 # 判斷結果
i = 0 # 循環(huán)次數(shù)
frequency = 3 # 循環(huán)限制次數(shù)
# 提示總猜測次數(shù)、剩余次數(shù)
print('WARNING: You have【{}】 chances you guess '.format(frequency), end = '--&&>>--')
print('【{}】 chances left now:\n'.format(frequency - i +1))
while result and i != frequency:
# 猜數(shù)字
num = int(input('Please guess a int_number:\n'))
result = judge_num(num, num_random)
i += 1
7.進制轉換
# 任意進制轉十進制
def other_to_decimal(hex, num):
# 整型轉化為列表,
num_str = str(num)
# map()將List對象中的元素(list類型)轉化為集合(set)類型
num_list = list(map(int, num_str))
# 列表反序
num_list = num_list[::-1]
print(list(map(int, num_str)))
# 獲取數(shù)字位數(shù)
digit = len(num_list)
num_decimal = 0
# 累加
for i in range(digit):
numi = num_list[i]
# print(numi, hex**i)
num_decimal += numi*(hex**i) # 對每一位數(shù)的冪指數(shù)累加
return num_decimal
# 十進制轉任意進制
def decimal_to_other(hex, num):
# 獲取數(shù)字位數(shù)
digit = len(str(num))
num_hex = []
quotient = 1
# 相除,余數(shù)計入列表num_hex
while quotient:
# 取余和取商
quotient = num // hex
remainder = num % hex
# print(quotient, remainder)
# 余數(shù)計入列表
num_hex.append(remainder)
# 商做下一次循環(huán)
num = quotient
# 列表反序,通過切片和sort()函數(shù)可以實現(xiàn)
num_hex = num_hex[::-1]
# num_hex.sort(reverse=True)
# 如果超過十進制,用ASCII碼轉化為字母
for i in range(len(num_hex)):
if num_hex[i] > 9:
num_hex[i] = chr(int(num_hex[i])+87)
# print(num_hex)
# 列表轉化為字符串
result = (''.join('%s' %m for m in num_hex))
return result
Type = bool(input("十進制轉任意進制請輸入1,任意進制轉十進制請輸入0\n"))
if Type:
hex = int(input("需要把十進制轉換為多少進制?請輸入正整數(shù)\n"))
num = int(input("需要轉換的數(shù)字是:"))
print("換算結果是:", decimal_to_other(hex, num))
else:
hex = int(input("需要把多少進制轉換為十進制?請輸入正整數(shù)\n年"))
num = int(input("需要轉換的數(shù)字是:"))
print("換算結果是:", other_to_decimal(hex, num))
到此這篇關于 7個關于Python的經(jīng)典基礎案例的文章就介紹到這了,更多相關Python 經(jīng)典案例內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在Python中操作列表之List.append()方法的使用
這篇文章主要介紹了在Python中操作列表之List.append()方法的使用,是Python入門學習中的基礎知識,需要的朋友可以參考下2015-05-05
python 提取tuple類型值中json格式的key值方法
今天小編就為大家分享一篇python 提取tuple類型值中json格式的key值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Opencv中cv2.cvtColor彩色圖轉灰度圖的其他6種方法
本文主要介紹了Opencv中cv2.cvtColor彩色圖轉灰度圖的其他6種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05

