Python初学者练习小实例(21-50例),1个实例多个列子相互参考

✍️Auth:star皆空       Date:2022/08/30       Cat:python相关       👁️:689 次浏览

以下所有测试实例来自于菜鸟教程:https://www.runoob.com/python3/python3-examples.html

目录

21、Python 最大公约数算法

最大公约数,也称最大公因数、最大公因子,指两个或多个整数共有约数中最大的一个。

个人参考代码

a = int(input("请输入整数a:"))
b = int(input("请输入整数b:"))
c = 0
if a >= b:
    for i in range(1,b+1):
        if a % i == 0 and b % i == 0:
            print(f"{i}为公约数")
            c = i
if b > a:
    for i in range(1,a+1):
        if a % i == 0 and b % i == 0:
            print(f"{i}为公约数")
            c = i
print(f"{c}为最大公约数")

执行结果

请输入整数a: 20
请输入整数b: 12
1为公约数                                                                                                                                                                                            
2为公约数                                                                                                                                                                                            
4为公约数                                                                                                                                                                                            
4为最大公约数 

菜鸟教程参考代码

def hcf(x, y):
   """该函数返回两个数的最大公约数"""

   # 获取最小值
   if x > y:
       smaller = y
   else:
       smaller = x

   for i in range(1,smaller + 1):
       if((x % i == 0) and (y % i == 0)):
           hcf = i

   return hcf


# 用户输入两个数字
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))

print( num1,"和", num2,"的最大公约数为", hcf(num1, num2))

执行以上代码输出结果为:

输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最大公约数为 6

其他人参考代码

可按以下思路减少循环次数:

  1. 当最小值为最大公约数时,直接返回;
  2. 当最小值不为最大公约数时,最大公约数不会大于最小值的1/2;
  3. 求最大公约数理应从大到小循环递减求最大。
def gcd(a, b):
    if b > a:
        a, b = b, a   # b为最小值
    if a % b == 0:
        return b      # 判断b是否为最大公约数
    for i in range(b//2+1, 1, -1):    # 倒序求最大公约数更合理
        if b % i == 0 and a % i == 0:
            return i
    return 0

while(True):
    a = int(input("Input 'a':"))
    b = int(input("Input 'b':"))
    print(gcd(a, b))

更简洁快速

def gcd(x, y): # very fast
   return x if y == 0 else gcd(y, x%y)

print(gcd(378, 5940))  # result: 54

22、Python 最小公倍数算法

最小公倍数两个或多个整数公有的倍数叫做它们的公倍数,其中除0以外最小的一个公倍数就叫做这几个整数的最小公倍数。

个人参考代码

a = int(input("请输入整数a:"))
b = int(input("请输入整数b:"))

i = 1
while True:
    i += 1
    if i % a == 0 and i % b == 0:
        print(f"最小公倍数是{i}")
        break

执行结果:

请输入整数a: 30
请输入整数b: 12
最小公倍数是60 

菜鸟教程参考代码

# 定义函数
def lcm(x, y):

   #  获取最大的数
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm


# 获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))

print( num1,"和", num2,"的最小公倍数为", lcm(num1, num2))

执行以上代码输出结果为:

输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最小公倍数为 216

其他人参考代码

按以下思路可减少循环次数:

1.当最大值为最小公倍数时,返回最大值;

2.当最大值不为最小公倍数时,最小公倍数为最大值的倍数。

# 最小公倍数
def lcm(a, b):
    if b > a:
        a, b = b, a     # a为最大值
    if a % b == 0:
        return a        # 判断a是否为最小公倍数
    mul = 2             # 最小公倍数为最大值的倍数
    while a*mul % b != 0:
        mul += 1
    return a*mul

while(True):
    a = int(input("Input 'a':"))
    b = int(input("Input 'b':"))
    print(lcm(a, b))

23、Python 简单计算器实现

个人参考代码

def jia(a,b):
    c = a + b
    return c
def jian(a,b):
    c = a - b
    return c
def chen(a,b):
    c = a * b
    return c
def chu(a,b):
    c = a / b
    return c
a = int(input("请输入a的值:"))
x = str(input("请输入运算(+ - * /)符号:"))
if    x == '+':
    b = int(input("请输入b的值:"))
#    jia(a,b)
    print(jia(a,b))
elif    x == '-':
    b = int(input("请输入b的值:"))
    print(jian(a,b))
elif    x == '*':
    b = int(input("请输入b的值:"))
    print(chen(a,b))
elif    x == '/':
    b = int(input("请输入b的值:"))
    print(chu(a,b))

执行结果:

请输入a的值:54
请输入运算(+ - * /)符号:/
请输入b的值:2
27.0

请输入a的值:32
请输入运算(+ - * /)符号:*
请输入b的值:4
128

请输入a的值:2
请输入运算(+ - * /)符号:-
请输入b的值:5
-3

菜鸟教程参考代码

# 定义函数
def add(x, y):
   """相加"""

   return x + y

def subtract(x, y):
   """相减"""

   return x - y

def multiply(x, y):
   """相乘"""

   return x * y

def divide(x, y):
   """相除"""

   return x / y

# 用户输入
print("选择运算:")
print("1、相加")
print("2、相减")
print("3、相乘")
print("4、相除")

choice = input("输入你的选择(1/2/3/4):")

num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))

if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("非法输入")

执行以上代码输出结果为:

选择运算:
1、相加
2、相减
3、相乘
4、相除
输入你的选择(1/2/3/4):2
输入第一个数字: 5
输入第二个数字: 2
5 - 2 = 3

其他人参考代码

很简单的计算器,在输入框中输入计算表达式(如:2+2),按 GET RESULT 就可以计算:

from math import *
try:
    from tkinter import *
except ImportError:
    from Tkinter import *
def calc():
    text = var.get()
    result = eval(text)
    result = result / 1.0
    result = str(result)
    var.set(result)
text = ''
result = ''
root = Tk()
pi = 3.1415926535897932
root.geometry('360x48')
root.resizable(width=False,height=False)
root.title('Mini Calculator')
var = StringVar()
entry = Entry(root,textvariable=var,width=360)
button = Button(root,text='GET RESULT',command=calc)
entry.pack()
button.pack()
root.mainloop()

24、Python 生成日历

引用包直接生成,相对简单

个人参考代码

import calendar

year = int(input("年份:"))
month = int(input("月份:"))

print(calendar.month(year,month))

执行结果

年份:2022
月份:8
    August 2022
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

菜鸟教程参考代码

教程参考差不多也一样

# 引入日历模块
import calendar

# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))

# 显示日历
print(calendar.month(yy,mm))

执行以上代码输出结果为:

输入年份: 2015
输入月份: 6
     June 2015
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

其他人参考代码

这个代码的缺点就是,我们日常用的日历都是星期天在前的。所以改进代码,应该加一行用以将星期天放在首位。

#生成日历
# 引入日历模块
import calendar

# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
calendar.setfirstweekday(firstweekday=6)#设置第一天是星期天

# 显示日历
print(calendar.month(yy,mm))

借鉴楼上的设置日期显示格式,将第一天设置为周日,写的一个显示一年 12 月份的日历

import calendar
calendar.setfirstweekday(firstweekday=6)    # 显示出一年 12 个月份的日历
while True:
    yy = int(input('input years:'))
    # mm = int(input('input month:'))
    for i in range(12):
        print(calendar.month(yy, i + 1))
        print('*' * 20)

25、Python 使用递归斐波那契数列

个人参考代码

a = 0
b = 1

##c = a + b
print(0)
for i in range(0,num):
    c = a + b
    a,b=b,c
    print(c)

执行结果:

次数:10
0
1
2
3
5
8
13
21
34
55
89

菜鸟教程参考代码

def recur_fibo(n):
   """递归函数
   输出斐波那契数列"""
   if n <= 1:
       return n
   else:
       return(recur_fibo(n-1) + recur_fibo(n-2))


# 获取用户输入
nterms = int(input("您要输出几项? "))

# 检查输入的数字是否正确
if nterms <= 0:
   print("输入正数")
else:
   print("斐波那契数列:")
   for i in range(nterms):
       print(recur_fibo(i))

执行以上代码输出结果为:

您要输出几项? 10
斐波那契数列:
0
1
1
2
3
5
8
13
21
34

其他人参考代码

def Fib(n):
    a, b = 0, 1
    while n:
        a, b, n = b, a + b, n - 1
        print(a)
Fib(7)

26、Python 文件 IO

个人参考代码

f = open("test.txt","w")
f.write("这是测试文档")
f.close()

f = open("test.txt","r")
print(f.read())
f.close()

执行结果:

这是测试文档

菜鸟教程参考代码

# 写文件
with open("test.txt", "wt") as out_file:
    out_file.write("该文本会写入到文件中\n看到我了吧!")

# Read a file
with open("test.txt", "rt") as in_file:
    text = in_file.read()

print(text)

执行以上代码输出结果为:

该文本会写入到文件中
看到我了吧!

注:with…as,就是个python控制流语句,像 if ,while一样。
with…as语句是简化版的try except finally语句。

其他人参考代码

w, r, wt, rt 都是 python 里面文件操作的模式。
w 是写模式,r 是读模式。
t 是 windows 平台特有的所谓 text mode(文本模式),区别在于会自动识别 windows 平台的换行符。
类 Unix 平台的换行符是 \n,而 windows 平台用的是 \r\n 两个 ASCII 字符来表示换行,python 内部采用的是 \n 来表示换行符。
rt 模式下,python 在读取文本时会自动把 \r\n 转换成 \n。
wt 模式下,Python 写文件时会用 \r\n 来表示换行。

在 Windows 下,文件路径前需要加 r 取消 \ 转义或者将 \ 用 \ 转义,否则会转码错误。

'''文件IO'''
with open(r'C:\Users\Administrator\Desktop\s.txt','wt') as fileout:
    fileout.write("写一行中文试试\n")
with open(r'C:\Users\Administrator\Desktop\s.txt','rt') as filein:
    print(filein.readline())

27、Python 字符串判断

个人参考代码

python自带方法

a = str(input("请输入值:"))

if a.isalpha() == True:
    print(f"{a}所以字符都是字母")
elif a.isdigit() == True:
    print(f"{a}所以字符都是数字")

执行结果:

请输入值:123
123所以字符都是数字

请输入值:asd
asd所以字符都是字母

菜鸟教程参考代码

# 测试实例一
print("测试实例一")
str = "runoob.com"
print(str.isalnum()) # 判断所有字符都是数字或者字母
print(str.isalpha()) # 判断所有字符都是字母
print(str.isdigit()) # 判断所有字符都是数字
print(str.islower()) # 判断所有字符都是小写
print(str.isupper()) # 判断所有字符都是大写
print(str.istitle()) # 判断所有单词都是首字母大写,像标题
print(str.isspace()) # 判断所有字符都是空白字符、\t、\n、\r

print("------------------------")

# 测试实例二
print("测试实例二")
str = "runoob"
print(str.isalnum())
print(str.isalpha())
print(str.isdigit())
print(str.islower())
print(str.isupper())
print(str.istitle())
print(str.isspace())

执行以上代码输出结果为:

测试实例一
False
False
False
True
False
False
False
------------------------
测试实例二
True
True
False
True
False
False

28、Python 字符串大小写转换

个人参考代码

a = str(input("请输入字母:"))
b = int(input("请选择1或者2,1转换成大写,2转换为小写:"))

if  b == 1:
    print(a.upper())
elif b == 2:
    print(a.lower())

执行结果:

请输入字母:qwer
请选择1或者2,1转换成大写,2转换为小写:1
QWER

请输入字母:AASD
请选择1或者2,1转换成大写,2转换为小写:2
aasd

菜鸟教程参考代码

str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 

执行以上代码输出结果为:

WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

29、Python 计算每个月天数

个人参考代码

也是根据下面菜鸟的参考代码改的

import calendar

year = int(input("年份:"))
mon = int(input("月份:"))

mr = calendar.monthrange(year,mon)

print(f"{year}年的{mon}月,总共有{mr[1]}天")

执行结果:

年份:2022
月份:2
2022年的2月,总共有28天

菜鸟教程参考代码

import calendar
monthRange = calendar.monthrange(2016,9)
print(monthRange)

执行以上代码输出结果为:

(3, 30)

输出的是一个元组,第一个元素是所查月份的第一天对应的是星期几(0-6),第二个元素是这个月的天数。以上实例输出的意思为 2016 年 9 月份的第一天是星期四,该月总共有 30 天。

其他人参考代码

若只是想知道每个月的天数,可用:

>>> calendar.mdays
[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

实例:

import calendar
print(calendar.mdays[9])

30、Python 获取昨天日期

菜鸟教程参考代码

# 引入 datetime 模块
import datetime
def getYesterday(): 
    today=datetime.date.today() 
    oneday=datetime.timedelta(days=1) 
    yesterday=today-oneday  
    return yesterday

# 输出
print(getYesterday())

执行以上代码输出结果为:

2015-06-10

其他人参考代码

让上面的方法更简洁:

# 引入 datetime 模块
import datetime

def getYesterday(): 
    yesterday = datetime.date.today() + datetime.timedelta(-1)
    return yesterday
# 输出
print(getYesterday())

31、Python 约瑟夫生者死者小游戏

30 个人在一条船上,超载,需要 15 人下船。

于是人们排成一队,排队的位置即为他们的编号。

报数,从 1 开始,数到 9 的人下船。

如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?

个人参考代码

参考了list的切片,每淘汰一个人,尾接头重新排序。依次循环。

people=[]
for x in range(1,31):
    add = str(x)
    people.append(add)
while True:
    print(f"{people[8]}号人员下船")
    del(people[8])
    people=people[8:]+people[:8]
    print(people)
    if len(people) <= 15:
        print(f"剩下的船员为{people}")
        break

执行结果:

9号人员下船
18号人员下船
27号人员下船
6号人员下船
16号人员下船
26号人员下船
7号人员下船
19号人员下船
30号人员下船
12号人员下船
24号人员下船
8号人员下船
22号人员下船
5号人员下船
23号人员下船
剩下的船员为['25', '28', '29', '1', '2', '3', '4', '10', '11', '13', '14', '15', '17', '20', '21']

菜鸟教程参考代码

30 个人在一条船上,超载,需要 15 人下船。

于是人们排成一队,排队的位置即为他们的编号。

报数,从 1 开始,数到 9 的人下船。

如此循环,直到船上仅剩 15 人为止,问都有哪些编号的人下船了呢?

people={}
for x in range(1,31):
    people[x]=1
# print(people)
check=0
i=1
j=0
while i<=31:
    if i == 31:
        i=1
    elif j == 15:
        break
    else:
        if people[i] == 0:
            i+=1
            continue
        else:
            check+=1
            if check == 9:
                people[i]=0
                check = 0
                print("{}号下船了".format(i))
                j+=1
            else:
                i+=1
                continue

执行以上实例,输出结果为:

9号下船了
18号下船了
27号下船了
6号下船了
16号下船了
26号下船了
7号下船了
19号下船了
30号下船了
12号下船了
24号下船了
8号下船了
22号下船了
5号下船了
23号下船

其他人参考代码

约瑟夫环是很经典的题目。以下代码充分利用 Python 数据结构的特性,以求尽可能简洁。

people=list(range(30))
while len(people)>15:
    i=1
    while i<9:
        people.append(people.pop(0))
        i+=1
    print('{:2d}号下船了'.format(people.pop(0)))

跟上边有几位同学的思路差不多,不过应该是最短的了,5 行:

sum = list(range(1,31))
while len(sum) > 15:
    print('{}号下船了'.format(sum.pop(8)))
    for i in range(8):
        sum.append(sum.pop(0))

32、Python 五人分鱼

A、B、C、D、E 五人在某天夜里合伙去捕鱼,到第二天凌晨时都疲惫不堪,于是各自找地方睡觉。

日上三杆,A 第一个醒来,他将鱼分为五份,把多余的一条鱼扔掉,拿走自己的一份。

B 第二个醒来,也将鱼分为五份,把多余的一条鱼扔掉拿走自己的一份。 。

C、D、E依次醒来,也按同样的方法拿鱼。

问他们至少捕了多少条鱼?

个人参考代码

菜鸟教程参考代码

def main():
    fish = 1
    while True:
        total, enough = fish, True
        for _ in range(5):
            if (total - 1) % 5 == 0:
                total = (total - 1)  //  5 * 4
            else:
                enough = False
                break
        if enough:
            print(f'总共有{fish}条鱼')
            break
        fish += 1


if __name__ == '__main__':
    main()

运行结果:

总共有3121条鱼

这个代码的思路是:
让鱼的总数 fish 从 1 开始递增,当 fish 的数量可以满足无论分鱼分配规则,那么这个 fish 值就是合伙捕鱼的最小值。

其他人参考代码

# n个人总共捕鱼数量为:S = Kn^n-(n-1) K为正整数
# 最后一个人分得鱼的数量为:S(n) = K(n-1)^(n-1)-1 K为正整数

# 至少捕鱼数(即K为1)
def min_fish(n):
    return n ** n - (n - 1)

if __name__ == '__main__':
    n = int(input('请输入人数:'))
    print('至少捕了{0}条鱼'.format(min_fish(n)))

递归解法:

def need(n , r):
    if n % 5 == 1:
        if r == 5:
            return True
        else:
            return need(n - (n - 1) / 5 -1, r + 1)
    else:
        return False
n = 6
while True:
    if need(n,1):
        break
    else:
        n = n + 5
print(n)

33、Python 实现秒表功能

个人参考代码

根据菜鸟简易版,直接ctrl+c 结束

import time

while True:
    input("回车开始")
    start = time.time()
    while True:
        try:
            pass
        except KeyboardInterrupt:
            end = time.time()
            print(f"时间为{round(end-start,4)}")

执行结果,最后报错结束。

回车开始
^C时间为3.0319
^C时间为4.5482
^C时间为6.0043
^C时间为6.6239
^C时间为7.1838
^C时间为7.5319
^C时间为7.8319
^C时间为8.1994
^CTraceback (most recent call last):
  File "time1.py", line 8, in <module>
    pass

菜鸟教程参考代码

import time

print('按下回车开始计时,按下 Ctrl + C 停止计时。')
while True:

    input("") # 如果是 python 2.x 版本请使用 raw_input() 
    starttime = time.time()
    print('开始')
    try:
        while True:
            print('计时: ', round(time.time() - starttime, 0), '秒', end="\r")
            time.sleep(1)
    except KeyboardInterrupt:
        print('结束')
        endtime = time.time()
        print('总共的时间为:', round(endtime - starttime, 2),'secs')
        break

测试结果为:

按下回车开始计时,按下 Ctrl + C 停止计时。

开始
计时:  3.0 秒
计时:  5.0 秒
^C结束 6.0 秒
总共的时间为: 6.69 secs

菜鸟相对更完善。

34、Python 计算 n 个自然数的立方和

个人参考代码

n = int(input("输入数字范围:"))
summ = 0
for i in range(n+1):
    summ = i**3 + summ
    print(summ) 

执行结果:

输入数字范围:9
2025

菜鸟教程参考代码

# 定义立方和的函数
def sumOfSeries(n):
    sum = 0
    for i in range(1, n+1):
        sum +=i*i*i

    return sum
# 调用函数
n = 5
print(sumOfSeries(n))

以上实例输出结果为:

225

其他人参考代码

使用列表解析式直接生成一个n次方列表,然后求和,便是前n个数3次方的和

print( sum([i**3 for i in range(1,int( input("请输入n的值:"))+1)]) )

35、Python 计算数组元素之和

个人参考代码

li = []
summ = 0
n = int(input("请输入数组位数:"))
for i in range(1,n+1):
    print(f"请输入第{i}位数字")
    a = int(input(""))
    li.append(a)

for j in range(n):
    summ = li[j] + summ
print(f"数组{li}的元素之和位{summ}")

执行结果:

请输入数组位数:5
请输入第1位数字
32
请输入第2位数字
12
请输入第3位数字
54
请输入第4位数字
2123
请输入第5位数字
65
数组[32, 12, 54, 2123, 65]的元素之和位2286

菜鸟教程参考代码

开始使用内置函数 sum直接求和。

# 定义函数,arr 为数组,n 为数组长度,可作为备用参数,这里没有用到
def _sum(arr,n):

    # 使用内置的 sum 函数计算
    return(sum(arr))

# 调用函数
arr=[]
# 数组元素
arr = [12, 3, 4, 15]

# 计算数组元素的长度
n = len(arr)

ans = _sum(arr,n)

# 输出结果
print ('数组元素之和为',ans)

以上实例输出结果为:

数组元素之和为 34

36、Python 数组翻转指定个数的元素

个人参考代码

个人逻辑,用切片组成新的数组

def cut(arr,d,n):
    arr=arr[d:]+arr[:d]
    return arr
arr=[1,2,3,4,5,6,7]
print(f"原数组{arr}")
print(cut(arr,2,7))

执行结果:

原数组[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5, 6, 7, 1, 2]

菜鸟教程参考代码

def leftRotate(arr, d, n):
    for i in range(d):
        leftRotatebyOne(arr, n)
def leftRotatebyOne(arr, n):
    temp = arr[0]
    for i in range(n-1):
        arr[i] = arr[i+1]
    arr[n-1] = temp


def printArray(arr,size):
    for i in range(size):
        print ("%d"% arr[i],end=" ")


arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

以上实例输出结果为:

3 4 5 6 7 1 2

实例 2

def leftRotate(arr, d, n):
    for i in range(gcd(d,n)):

        temp = arr[i]
        j = i
        while 1:
            k = j + d
            if k >= n:
                k = k - n
            if k == i:
                break
            arr[j] = arr[k]
            j = k
        arr[j] = temp

def printArray(arr, size):
    for i in range(size):
        print ("%d" % arr[i], end=" ")

def gcd(a, b):
    if b == 0:
        return a;
    else:
        return gcd(b, a%b)

arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2, 7)
printArray(arr, 7)

实例3

def rverseArray(arr, start, end):
    while (start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end = end-1

def leftRotate(arr, d):
    n = len(arr)
    rverseArray(arr, 0, d-1)
    rverseArray(arr, d, n-1)
    rverseArray(arr, 0, n-1)

def printArray(arr):
    for i in range(0, len(arr)):
        print (arr[i], end=' ')

arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2)
printArray(arr)

其他人参考代码

若是从首个元素向最后翻转,感觉这种方法要简单些。

定义函数:

def reversal(lst,n):
    for x in range(n):
        lst.append(arr.pop(0))
    return lst   

# 调用
arr = [1, 2, 3, 4, 5, 6, 7]
reversal(arr,3)

37、Python 将列表中的头尾两个元素对调

个人参考代码

def change(li):
    li.insert(-1,li[0])
    del(li[-1])
    li.insert(1,li[-1])
    del(li[1])
    return li
li=[1,2,3,4,5,6,7,8,9]
print(change(li))

执行结果:

[9, 2, 3, 4, 5, 6, 7, 8, 1]

菜鸟教程参考代码

实例1:

def swapList(newList):
    size = len(newList)

    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp

    return newList

newList = [1, 2, 3]

print(swapList(newList))

实例2:

def swapList(newList):

    newList[0], newList[-1] = newList[-1], newList[0]

    return newList

newList = [1, 2, 3]
print(swapList(newList))

实例3

def swapList(list):

    get = list[-1], list[0]

    list[0], list[-1] = get

    return list

newList = [1, 2, 3]
print(swapList(newList))

其他人参考代码

应该是最简洁的代码了:

arr = list(map(int,input("请输入数组:").split()))
arr[0], arr[-1] = arr[-1], arr[0]
print(arr)

38、Python 将列表中的指定位置的两个元素对调

个人参考代码

根据上面提供的方法,简单点

def change(li,a,b):
    li[a-1],li[b-1]=li[b-1],li[a-1]
    return li
li=[1,2,3,4,5,6,7,8,9]
print(change(li,1,4))

执行结果:

[4, 2, 3, 1, 5, 6, 7, 8, 9]

菜鸟教程参考代码

实例1:

def swapPositions(list, pos1, pos2):

    list[pos1], list[pos2] = list[pos2], list[pos1]
    return list

List = [23, 65, 19, 90]
pos1, pos2  = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

实例2:

def swapPositions(list, pos1, pos2):

    first_ele = list.pop(pos1)    
    second_ele = list.pop(pos2-1)

    list.insert(pos1, second_ele)  
    list.insert(pos2, first_ele)  

    return list

List = [23, 65, 19, 90]
pos1, pos2  = 1, 3

print(swapPositions(List, pos1-1, pos2-1))

实例3:

def swapPositions(list, pos1, pos2):

    get = list[pos1], list[pos2]

    list[pos2], list[pos1] = get

    return list

List = [23, 65, 19, 90]

pos1, pos2  = 1, 3
print(swapPositions(List, pos1-1, pos2-1))

以上实例输出结果为:

[19, 65, 23, 90]

其他人参考代码

引入中间变量:

def reversal(list,n1,n2):
    temp = list[n1]
    list[n1] = list[n2]
    list[n2] = temp
    print(list)
list = [1,2,3,4,5,6,7]
reversal(list,4,5)

39、Python 翻转列表

个人参考代码

自带参数reverse反转/倒序排序

li = [1,2,3,4,5]
li.reverse()

print(li)

执行结果:

[5, 4, 3, 2, 1]

菜鸟教程参考代码

实例 1

def Reverse(lst):
    return [ele for ele in reversed(lst)]

lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

实例 2

def Reverse(lst):
    lst.reverse()
    return lst

lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

实例 3

def Reverse(lst):
    new_lst = lst[::-1]
    return new_lst

lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))

其他人参考代码

还可以直接调用 list 列表的 sort 方法, 设置 reverse 为 True 即可翻转列表:

li = [*range(10, 16)]
# 得到列表 li = [10, 11, 12, 13, 14, 15], * 为解包符号
print(li)

# 降序排列
li.sort(reverse = True)
print(li)
# 输出: [15, 14, 13, 12, 11, 10]

40、Python 判断元素是否在列表中存在

菜鸟教程参考代码

实例 1

test_list = [ 1, 6, 3, 5, 3, 4 ]

print("查看 4 是否在列表中 ( 使用循环 ) : ")

for i in test_list:
    if(i == 4) :
        print ("存在")

print("查看 4 是否在列表中 ( 使用 in 关键字 ) : ")

if (4 in test_list):
    print ("存在")

以上实例输出结果为:

查看 4 是否在列表中 ( 使用循环 ) : 
存在
查看 4 是否在列表中 ( 使用 in 关键字 ) : 
存在

实例 2

# 初始化列表
test_list_set = [ 1, 6, 3, 5, 3, 4 ]
test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]

print("查看 4 是否在列表中 ( 使用 set() + in) : ")

test_list_set = set(test_list_set)
if 4 in test_list_set :
    print ("存在")

print("查看 4 是否在列表中 ( 使用 count()) : ")

if test_list_bisect.count(4) > 0 :
    print ("存在")

以上实例输出结果为:

查看 4 是否在列表中 ( 使用 set() + in) : 
存在
查看 4 是否在列表中 ( 使用 count()) : 
存在

41、Python 清空列表

菜鸟教程参考代码

定义一个列表,并清空列表,可以使用 clear() 方法实现。

实例 1

RUNOOB = [6, 0, 4, 1]
print('清空前:', RUNOOB)  

RUNOOB.clear()
print('清空后:', RUNOOB)  

以上实例输出结果为:

清空前: [6, 0, 4, 1]
清空后: []

42、Python 移除列表中重复的元素

菜鸟教程参考代码

知识点有:

Python 集合:集合(set)是一个无序的不重复元素序列。

Python 列表:列表是一种数据项构成的有限序列,即按照一定的线性顺序排列而成的数据项的集合,在这种数据结构上进行的基本操作包括对元素的的查找、插入和删除。

实例

list_1 = [1, 2, 1, 4, 6]

print(list(set(list_1)))

执行以上代码输出结果为:

[1, 2, 4, 6]

在以上实例中,我们首先将列表转换为集合,然后再次将其转换为列表。集合中不能有重复元素,因此 set() 会删除重复的元素。

删除两个列表中重复的元素
在以下实例中,两个列表中同时存在的元素会被删除。
实例

list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]

print(list(set(list_1) ^ set(list_2)))

首先,使用 set() 将两个列表转换为两个集合,用于删除列表中的重复元素。

然后,使用 ^ 运算符得到两个列表的对称差。
执行以上代码输出结果为:

[4, 6, 7, 8]

首先,将两个列表转换为两个集合,以从每个列表中删除重复项。 然后,^ 得到两个列表的对称差(排除两个集合的重叠元素)。

43、Python 复制列表

菜鸟教程参考代码

定义一个列表,并将该列表元素复制到另外一个列表上。

实例 1

def clone_runoob(li1):
    li_copy = li1[:]
    return li_copy

li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_runoob(li1)
print("原始列表:", li1)
print("复制后列表:", li2)

以上实例输出结果为:

原始列表: [4, 8, 2, 10, 15, 18]
复制后列表: [4, 8, 2, 10, 15, 18]

实例 2: 使用 extend() 方法

def clone_runoob(li1):
    li_copy = []
    li_copy.extend(li1)
    return li_copy

li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_runoob(li1)
print("原始列表:", li1)
print("复制后列表:", li2)

实例 3: 使用 list() 方法

def clone_runoob(li1):
    li_copy = list(li1)
    return li_copy

li1 = [4, 8, 2, 10, 15, 18]
li2 = clone_runoob(li1)
print("原始列表:", li1)
print("复制后列表:", li2)

44、Python 计算列表元素之和

菜鸟教程参考代码

实例 1

total = 0

list1 = [11, 5, 17, 18, 23]  

for ele in range(0, len(list1)):
    total = total + list1[ele]

print("列表元素之和为: ", total)

以上实例输出结果为:

列表元素之和为:  74

实例 2: 使用 while() 循环

total = 0
ele = 0

list1 = [11, 5, 17, 18, 23]  

while(ele < len(list1)):
    total = total + list1[ele]
    ele += 1

print("列表元素之和为: ", total)

实例 3: 使用递归

list1 = [11, 5, 17, 18, 23]

def sumOfList(list, size):
   if (size == 0):
     return 0
   else:
     return list[size - 1] + sumOfList(list, size - 1)

total = sumOfList(list1, len(list1))

print("列表元素之和为: ", total)

其他人参考代码

使用 reduce 函数:

from functools  import reduce

list1 = [11, 5, 17, 18, 23]
sum=reduce(lambda x,y:x+y,list1)
print(sum)

直接用 sum 函数求解

list1 = [11, 5, 17, 18, 23]

print("列表元素之和为: ", sum(list1))

45、Python 计算列表元素之积

菜鸟教程参考代码

实例 1

def multiplyList(myList) :

    result = 1
    for x in myList:
         result = result * x  
    return result  

list1 = [1, 2, 3]  
list2 = [3, 2, 4]
print(multiplyList(list1))
print(multiplyList(list2))

以上实例输出结果为:

6
24

其他人参考代码

from functools import reduce
list1 = [1,3,5,6,7]
sum = reduce(lambda x,y:x*y,list1)
print(sum)

采用递归方法:

def list_product(list_1,size):
    if size == 0:
        return 1    
    else:
        return list_1[size-1] * list_product(list_1,size - 1)


list_1 = [i for i in range(3,6)] #生成列表[3,4,5]
print(list_1)
print(list_product(list_1,len(list_1)))

46、Python 查找列表中最小元素

菜鸟教程参考代码

实例 1

list1 = [10, 20, 4, 45, 99]

list1.sort()

print("最小元素为:", *list1[:1])

以上实例输出结果为:

最小元素为: 4

实例 2:使用 min() 方法

list1 = [10, 20, 1, 45, 99]

print("最小元素为:", min(list1))

以上实例输出结果为:

最小元素为: 1

47、Python 查找列表中最大元素

菜鸟教程参考代码

实例 1

list1 = [10, 20, 4, 45, 99]

list1.sort()

print("最大元素为:", list1[-1])

以上实例输出结果为:

最大元素为: 99

实例 2:使用 max() 方法

list1 = [10, 20, 1, 45, 99]

print("最大元素为:", max(list1))

以上实例输出结果为:

最大元素为: 99

48、Python 判断字符串是否存在子字符串

给定一个字符串,然后判断指定的子字符串是否存在于该字符串中。

菜鸟教程参考代码

实例

def check(string, sub_str): 
    if (string.find(sub_str) == -1): 
        print("不存在!") 
    else: 
        print("存在!") 

string = "www.runoob.com"
sub_str ="runoob"
check(string, sub_str)

执行以上代码输出结果为:

存在!

其他人参考代码

string = "www.runoob.com"
sub_str ="runoob"
if sub_str in string:
    print('存在')
else:
    print('不存在')

49、Python 判断字符串长度

给定一个字符串,然后判断该字符串的长度。

菜鸟教程参考代码

实例 1:使用内置方法 len()

str = "runoob"
print(len(str))

执行以上代码输出结果为:

6

实例 2:使用循环计算

def findLen(str): 
    counter = 0
    while str[counter:]: 
        counter += 1
    return counter 

str = "runoob"
print(findLen(str))

其他人参考代码

def length(src):
    # 字符串长度
    count = 0
    all_str = src[count:]

    for x in all_str:
        count += 1

    print("字符串长度为: %s" % count)

src = "Runoob"
length(src)

50、Python 使用正则表达式提取字符串中的 URL

给定一个字符串,里面包含 URL 地址,需要我们使用正则表达式来获取字符串的 URL。

菜鸟教程参考代码

import re 

def Find(string): 
    # findall() 查找匹配正则表达式的字符串
    url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
    return url 


string = 'Runoob 的网页地址为:https://www.runoob.com,Google 的网页地址为:https://www.google.com'
print("Urls: ", Find(string))

?: 说明:

(?:x)

匹配 x 但是不记住匹配项。这种括号叫作非捕获括号,使得你能够定义与正则表达式运算符一起使用的子表达式。看看这个例子 /(?:foo){1,2}/。如果表达式是 /foo{1,2}/,{1,2} 将只应用于 ‘foo’ 的最后一个字符 ‘o’。如果使用非捕获括号,则 {1,2} 会应用于整个 ‘foo’ 单词。

执行以上代码输出结果为:

Urls:  ['https://www.runoob.com', 'https://www.google.com']
打赏作者
⚑Tags:      

发表评论