Python笔记

停止更新,见石墨

 

2020-09-29

1.range函数

from random import *
print(set(range(1,10,3)))   #可以用集合函数{1, 4, 7}
s=range(1,10,3)
print(s)                    #如果直接用range会显示原本文本range(1,10,3)
l=list(range(1,21,3))
print(l)                    #最常用的还是列表[1, 4, 7, 10, 13, 16, 19]

#range(起点闭区间,终点开区间,step可以省略)全部是整数,step默认为1,可以倒着数为负
#range外面要套上函数

2.while语句

2.1 求年数:自然增长率……

import math
x=13.95
n=0
while x<27.9:
    n+=1
    x=x*(1+0.00381)
    
print(n,x)

2020-10-01

2.2 最大公约数

ver1 短除法

m,n=eval(input('输入两个数:'))

g=min(m,n)
while not(m%g==0 and n%g==0):       #当g不能同时被m,n整除时候
    g-=1
    
print('最大公约数为:',g)

ver2 辗转相除

m,n=eval(input('2 int:'))

if m<n:
    m,n=n,m                 #exchange
    
while m%n!=0:
    r=m%n                   #r是余数,所以始终有r<n,再次赋值不用排序
    m=n
    
print('最大公约数为:',r)

ver3.1 相减

m,n=eval(input('2 int:'))

if m<n:
    m,n=n,m                 #exchange
    
while m-n!=0:
  
    a=max(m-n,n)
    b=min(m-n,n)
    m=a
    n=b
      
print('最大公约数为:',n)

ver3.2 相减

    r=m-n
    m=max(r,n)
    n=min(r,n)  
#while 语句内更换,use r,if only use m-n :m,n,m-n can't be recognized

3.循环结构的嵌套

 3.1 九九乘法表

ver1 有重复

for i in range(1,10):                        #[1,10)左闭右开整数
    for j in range(1,10):
        print('%d*%d=%2d  '%(i,j,i*j),end='')#%2d表示两个占位符,两个空格表示每算完一次就用两个空格隔开
    print('|')                               #在每行末加竖线
运行结果:

1*1= 1  1*2= 2  1*3= 3  1*4= 4  1*5= 5  1*6= 6  1*7= 7  1*8= 8  1*9= 9  |
2*1= 2  2*2= 4  2*3= 6  2*4= 8  2*5=10  2*6=12  2*7=14  2*8=16  2*9=18  |
3*1= 3  3*2= 6  3*3= 9  3*4=12  3*5=15  3*6=18  3*7=21  3*8=24  3*9=27  |
4*1= 4  4*2= 8  4*3=12  4*4=16  4*5=20  4*6=24  4*7=28  4*8=32  4*9=36  |
5*1= 5  5*2=10  5*3=15  5*4=20  5*5=25  5*6=30  5*7=35  5*8=40  5*9=45  |
6*1= 6  6*2=12  6*3=18  6*4=24  6*5=30  6*6=36  6*7=42  6*8=48  6*9=54  |
7*1= 7  7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49  7*8=56  7*9=63  |
8*1= 8  8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64  8*9=72  |
9*1= 9  9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81  |

ver2 下三角

for i in range(1,10):                        #[1,10)左闭右开整数
    j=1
    while j<=i:
        print('%d*%d=%2d  '%(i,j,i*j),end='')#%2d表示两个占位符
        j+=1                                 #j=j+1
    print('|')                               #在每行末加竖线
运行结果:

1*1= 1  |
2*1= 2  2*2= 4  |
3*1= 3  3*2= 6  3*3= 9  |
4*1= 4  4*2= 8  4*3=12  4*4=16  |
5*1= 5  5*2=10  5*3=15  5*4=20  5*5=25  |
6*1= 6  6*2=12  6*3=18  6*4=24  6*5=30  6*6=36  |
7*1= 7  7*2=14  7*3=21  7*4=28  7*5=35  7*6=42  7*7=49  |
8*1= 8  8*2=16  8*3=24  8*4=32  8*5=40  8*6=48  8*7=56  8*8=64  |
9*1= 9  9*2=18  9*3=27  9*4=36  9*5=45  9*6=54  9*7=63  9*8=72  9*9=81  |

ver3 上三角

for i in range(1,10):                        #[1,10)左闭右开整数
    j=i
    while j<=9:
        print('%d*%d=%2d  '%(i,j,i*j),end='')#%2d表示两个占位符
        j+=1                                 #j=j+1
    print('|')                               #在每行末加竖线
运行结果:

1*1= 1  1*2= 2  1*3= 3  1*4= 4  1*5= 5  1*6= 6  1*7= 7  1*8= 8  1*9= 9  |
2*2= 4  2*3= 6  2*4= 8  2*5=10  2*6=12  2*7=14  2*8=16  2*9=18  |
3*3= 9  3*4=12  3*5=15  3*6=18  3*7=21  3*8=24  3*9=27  |
4*4=16  4*5=20  4*6=24  4*7=28  4*8=32  4*9=36  |
5*5=25  5*6=30  5*7=35  5*8=40  5*9=45  |
6*6=36  6*7=42  6*8=48  6*9=54  |
7*7=49  7*8=56  7*9=63  |
8*8=64  8*9=72  |
9*9=81  |

4.跳转类语句 break,continue,pass以及else

break:退出该循环

continue:短路语句,退出本次循环,进入下一次循环

pass:空循环的延迟作用

方法:在if等循环语句里面加,要tab

 

4.1 pass

for c in 'asw':
    print(c,end='')
    for j in range(1,1000000):
        pass



运行结果:

asw(过了一会儿)

4.2 素数

ver1 else子句

c=0
for m in range (2,100):         #在[2,100)整数之间取m
    for j in range (2,m):       #j作为除数,只能在m的取值范围里面找
        if m%j==0:              #如果不能整除,那么退出上一排for循环
            break
    else:                       #如果退出该for循环,那么print出这个m的值
        print(m,end='\t')
        c+=1                    #c代表print的个数
        if c%8==0:
            print('')           #每8个数换行

>>>
2	3	5	7	11	13	17	19	
23	29	31	37	41	43	47	53	
59	61	67	71	73	79	83	89	
97	

2020-10-09

ver2 一般语言处理

c=0

for m in range(2,100):
    tag=True                       #默认假设m的tag是True,即m是素数
    for j in range(2,m):
         if m%j==0:
             tag=False              #如果m不是素数,那么tag变成False
             break                  #退出for j 循环,进入下一个m+1的for循环,tag又变回True
     
    if tag==True:
        print(m,end='\t')           #加制表符使对齐
        c+=1
        if c%8==0:
            print('')               #满8个数就换行,print自带换行

>>>2	3	5	7	11	13	17	19	
23	29	31	37	41	43	47	53	
59	61	67	71	73	79	83	89	
97	

 

4.3 while 1 :计算斐波那契数列到项值<=800

a,b=0,1
print(a,b,end=' ')
while 1:
    a,b=b,a+b
    if a+b>800:
        break
    print(a+b,end=' ')


>>>
0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 

while 1:一直循环下去,里面必须有一个break否则不会停

4.4 else

Python的else可以用于if,还有for,while

for,while与else同格,进入else的条件是从完整的循环里面出来,


5.数字字符图

5.1 有规律数值

t=0
for i in range(1,10):
    t=10*t+i
    print((9-i)*' ',t)


>>>
         1
        12
       123
      1234
     12345
    123456
   1234567
  12345678
 123456789

5.2 有规律数字图

5.2.1

ver1 无空格

t=0
for i in range(1,10):
    t=t*10+i
    print('%s%d×8+%d=%d'%((11-i)*'',t,i,t*8+i))


>>>
1×8+1=9
12×8+2=98
123×8+3=987
1234×8+4=9876
12345×8+5=98765
123456×8+6=987654
1234567×8+7=9876543
12345678×8+8=98765432
123456789×8+9=987654321

ver2.1 加空格法一

t=0
for i in range(1,10):
    t=t*10+i
    print('%s%d×8+%d=%d'%((11-i)*' ',t,i,t*8+i))          #在后面加空格这里i=1了已经,%s string就是空格的占位符


>>>
           1×8+1=9
          12×8+2=98
         123×8+3=987
        1234×8+4=9876
       12345×8+5=98765
      123456×8+6=987654
     1234567×8+7=9876543
    12345678×8+8=98765432
   123456789×8+9=987654321

ver2.2 加空格法二

t=0
for i in range(1,10):
    t=t*10+i
    print((9-i)*' ','%d×8+%d=%d'%(t,i,t*8+i))
#print里面的重复选项,如果中间加了逗号,可以只重复离得最近的引号,如果没有加逗号,那么默重复()内的所有引号内容
#print()里面可以有多个引号


>>>
         1×8+1=9
        12×8+2=98
       123×8+3=987
      1234×8+4=9876
     12345×8+5=98765
    123456×8+6=987654
   1234567×8+7=9876543
  12345678×8+8=98765432
 123456789×8+9=987654321

5.2.2

t=0
for i in range(1,10):
    t=10*t+1
    print((18-2*i)*' ','%d×%d=%d'%(t,t,t*t))


>>>
                 1×1=1
               11×11=121
             111×111=12321
           1111×1111=1234321
         11111×11111=123454321
       111111×111111=12345654321
     1111111×1111111=1234567654321
   11111111×11111111=123456787654321
 111111111×111111111=12345678987654321

5.2.3

t=0
for i in range(9,1,-1):
    t=10*t+i
    print((i-1)*' ','%d×9+%d=%d'%(t,(i-2),(t*9+i-2)))


>>>
         9×9+7=88
        98×9+6=888
       987×9+5=8888
      9876×9+4=88888
     98765×9+3=888888
    987654×9+2=8888888
   9876543×9+1=88888888
  98765432×9+0=888888888

5.3 反序数值

5.3.1 规定位数的传统方法

x=int(input('x四位整数:'))

a=x//1000
b=x//100%10
c=x//10%10
d=x%10

t=1000*d+100*c+10*b+a

print(t)


>>>
x四位整数:1234
4321

5.3.2 循环结构(不规定位数)

x=int(input('x整数:'))
t=0

while x>0:
    a=x%10
    x=x//10
    print(a,end='')                 #这里的a只是一个数字1,不是54321五位数


>>>
x整数:54321
12345

2020-10-11

6.综合应用

6.1 字符串加密

s=input('input an uncoded string:')
code=''             #construct a nil string
for c in s:
    if 'a'<=c<='z':
        num=ord(c)+5        #the coded order=original+5
        if num>ord('z'):
            num=num-26      #if it is beyond the alphabet order,just -26 thus all characters can be used
    if 'A'<=c<='Z':
        num=ord(c)+5
        if num>ord('Z'):
            num=num-26
    code+=chr(num)        
    
print('the coded string is:',code)


>>>
input an uncoded string:abcdefghijklmnopqrstuvwxyzABC
the coded string is: fghijklmnopqrstuvwxyzabcdeFGH

ord()里面只能加单个字符串,所以要打引号,但如果是上述代码中的c,定义c就是s的一个子字符串,因此没有加引号

chr()里面直接写数字即可

6.2 计算部分级数和:阶乘求e

e=n=i=1

while 1/n>=0.00001:
    n*=i
    e+=1/n
    i+=1
print('计算了%d项的e的值是:%9.5f'%(i,e))  #the lenth of the e is 7 and add 2 at the beginning

>>>
计算了10项的e的值是:  2.71828

6.3 阶乘

#求s=1!+2!+3!+4!+…+n!
s=0
n=int(input('choose a number:'))

for i in range (1,n+1):
    k=1
    for j in range(1,1+i):
        k*=j
        j+=1
    s+=k
    
print(s)

6.4 寻找1000之内,个位+十位+百位=5的数

num=0
for n in range (1,1001):
    a=n%10
    c=n//100
    b=n//10%10
    x=a+b+c
    if x==5:
        num+=1
        print(n,'')
        
print(num)


>>>
5 
14 
23 
32 
41 
50 
104 
113 
122 
131 
140 
203 
212 
221 
230 
302 
311 
320 
401 
410 
500 
21

 

6.5 数and format

6.5.1

n=int(input('input a number as line:'))

for i in range(1,n+1):
    print('{}{}{}{}'.format((n-i)*' ',(i-1)*'*','|',(i-1)*'*'))



>>>
input a number as line:6
     |
    *|*
   **|**
  ***|***
 ****|****
*****|*****

 

6.5.2

n=int(input('请输入奇数行数:'))
n=n//2+1
i=1
while i<=n:
    print("{}{}{}{}".format(' '*(n-i),'*'*(i-1),'|','*'*(i-1)))
    i += 1
i = n-1
while i>=1:
    print("{}{}{}{}".format(' '*(n-i),'*'*(i-1),'|','*'*(i-1)))
    i -= 1


>>>
请输入奇数行数:7
   |
  *|*
 **|**
***|***
 **|**
  *|*
   |

 6.6 字母金字塔

n=int(input('请输入行数:'))

for i in range (1,n+1):
    str=''
    j=1
    while j<=i:       
        str+=chr(64+j)
        j+=1
    spec=(n-i)*' '
    k=1
    while k<=i-1:
        str+=chr(64+i-k)
        k+=1
    print('%s%s'%(spec,str))



>>>
请输入行数:8
       A
      ABA
     ABCBA
    ABCDCBA
   ABCDEDCBA
  ABCDEFEDCBA
 ABCDEFGFEDCBA
ABCDEFGHGFEDCBA

7.format格式化函数

摘自菜鸟教程:

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'

也可以设置参数:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

 

输出结果为:

网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com

也可以向 str.format() 传入对象:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

输出结果为:

value 为: 6

#8.列表lst.append('一个字符串')和数字转字符串str()

lst3=[]
lst7=[]
for i in range(1,101):
    if i%3==0:
        a=str(i)
        lst3.append(i)
        
    if i%3==0:
        a=str(i)
        lst7.append(i)
print('3的倍数有:',lst3)
print('7的倍数有:',lst7)




>>>
3的倍数有: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
7的倍数有: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]

#9.字符串的反向

i=1
s=input('input a string:')
length=len(s)
print('the lenth of the string is:',length)
for c in s:
    print(s[length-i],end='')
    i+=1


>>>
input a string:ABXVH
the lenth of the string is: 5
HVXBA

8.函数

8.1 定义函数def <function name>(参量 可有多个,可无,逗号隔开)

定义的function可以在不同的file里面使用

return <新加入的变量,e.g. y>:完成函数的定义

8.1.1 用三个三角形来进行五边形面积的计算

import math


def tri(x,y,z):
    c=(x+y+z)/2
    area=math.sqrt(c*(c-x)*(c-y)*(c-z))
    return area

s=input('请输入a,b,c,d,e,f,g的值,divided by空格:')
t=s.split()
a,b,c,d,e,f,g=list(map(float,t))  #不懂map和float(换成int也一样的效果)
tr1=tri(a,b,c)
tr2=tri(c,e,d)
tr3=tri(e,f,g)

area=tr1+tr2+tr3   #area已经被tri()函数定义了为什么还可以相加
print(area)



>>>
请输入a,b,c,d,e,f,g的值,divided by空格:1 2 3 4 5 6 7
20.69693845669907

8.1.2 自定义HandleList函数

HR:abbr for HandleList

def HL(x):
    for i in range(len(x)):
        if i%2==0:
            x[i]+=1
        else:
            x[i]-=1


s=[1,2,3,4]                         #这里list里面的是数字,不能是'1'之类的,也不能'1'和1混用
print('the original list is:',s)
HL(s)
print('the handled one is:',s)


>>>
the original list is: [1, 2, 3, 4]
the handled one is: [2, 1, 4, 3]

8.1.3 一元二次方程求解

import math

def QE(a,b,c):
    d=b*b-4*a*c
    if d>=0:
        x1=(-b+math.sqrt(d))/(2*a)
        x2=(-b-math.sqrt(d))/(2*a)
        print(x1,x2)
        
    else:
        print('无实根')
    

m,n,p=eval(input('please input m,n,p:'))
QE(m,n,p)

8.2 形参和实参

形参:未知参数。默认值参数,可变长度参数

其中 def function(<未知参数1>,…,<未知参数n>,<默认值参数1=?>,…,<默认值参数n=?>)

未知在前,默认在后,并且默认可以在调用函数的时候省略,此时就是默认参数的默认值,也可改变默认参数的值

8.2.1 默认参数的使用

def strhandle(argstr,times=1):
    return argstr*times

str='字符串'
print(strhandle(str))            #这里的str是形参,argstr是实参

>>>字符串

str2=['list',3]
print(strhandle(str2))

>>>['list',3]

str3='can not change the time'
times=2
print(strhandle(str3))

>>>can not change the time       #这里的函数里面没有调用新的times,必须要写进函数才可以

str4='change the time'
times=2
print(strhandle(str3,times))

>>>change the timechange the time

str4='change the time'
print(strhandle(str4,times=4)) or print(strhandle(str4,4))

>>>change the timechange the timechange the timechange the time    #also can defite a new time in the function


str5='change the time for twice'
times=2
print(strhandle(str5,times=5))

>>>change the time for twicechange the time for twicechange the time for twicechange the time for twicechange the time for twice

8.2.2 可变长度参数

<*argu>:元组

<**argu>:键值对

def calcu(cmd,*data):
        if cmd=='求平均值':
            s=sum(data)/len(data)
            return s
        elif cmd=='求和':
            s=sum(data)
            return s
        else:
            for i in data:
                s=1
                s*=i
            return s
        
print(calcu('求和',12,3,5,3.5,6,4))


>>>
35.5

8.3 递归函数

直接递归调用,间接递归调用

8.3.1 求输入n的阶乘

def fact(n):
    if n==1:
        return 1
    else:
        return n*fact(n-1)
data=int(input('输入数字:'))   
print(fact(data))


>>>
输入数字:4
24


输入数字:5
120

8.3.2 字符串逆转

def rev(s):
    if len(s)==1:
        return s
    else:
        return rev(s[1:])+s[0]
    
print(rev('ABCDE'))



>>>
EDCBA

8.3.3 递归分析:画图

matplotlib
This is an object-oriented plotting library.

A procedural interface is provided by the companion pyplot module, which may be imported directly, e.g.:

import matplotlib.pyplot as plt
or using ipython:

ipython
at your terminal, followed by:

In [1]: %matplotlib
In [2]: import matplotlib.pyplot as plt
at the ipython shell prompt.

For the most part, direct use of the object-oriented library is encouraged when programming; pyplot is primarily for working interactively. The exceptions are the pyplot commands figure(), subplot(), subplots(), and savefig(), which can greatly simplify scripting.

Modules include:

matplotlib.axes
defines the Axes class. Most pyplot commands are wrappers for Axes methods. The axes module is the highest level of OO access to the library.

matplotlib.figure
defines the Figure class.

matplotlib.artist
defines the Artist base class for all classes that draw things.

matplotlib.lines
defines the Line2D class for drawing lines and markers

matplotlib.patches
defines classes for drawing polygons

matplotlib.text
defines the Text, TextWithDash, and Annotate classes

matplotlib.image
defines the AxesImage and FigureImage classes

matplotlib.collections
classes for efficient drawing of groups of lines or polygons

matplotlib.colors
classes for interpreting color specifications and for making colormaps

matplotlib.cm
colormaps and the ScalarMappable mixin class for providing color mapping functionality to other classes

matplotlib.ticker
classes for calculating tick mark locations and for formatting tick labels

matplotlib.backends
a subpackage with modules for various gui libraries and output formats

The base matplotlib namespace includes:

rcParams
a global dictionary of default configuration settings. It is initialized by code which may be overridden by a matplotlibrc file.

rc()
a function for setting groups of rcParams values

use()
a function for setting the matplotlib backend. If used, this function must be called immediately after importing matplotlib for the first time. In particular, it must be called before importing pyplot (if pyplot is imported).

matplotlib was initially written by John D. Hunter (1968-2012) and is now developed and maintained by a host of others.

Occasionally the internal documentation (python docstrings) will refer to MATLAB&reg;, a registered trademark of The MathWorks, Inc.

 

e.g.1

import matplotlib.pyplot as plt
x=[0,300,150]
y=[300,300,0]
plt.plot(x,y,'b')  #x,y进行连线,颜色为blue,其中连线规则为:(x[0],y[0])-->(x[1],y[1])-->如果不回到原点不会自动闭合连线
plt.show()  #显示图形

e.g.2***

import matplotlib.pyplot as plt
def trigraph(x,y,n):
    x1,x2,x3=x      #对列表x序列解包,不能用*x
    y1,y2,y3=y
    if n==2:
        x=[x1,x2,x3,x1]  #这里列表都有4个元素的原因是要形成一个闭合的图形,回到原点
        y=[y1,y2,y3,y1]
        plt.plot(x,y,'r')
    else:
        u1=(x1+x2)/2;v1=(y1+y2)/2  #有规律,先直接假设只这样画一次图
        u2=(x2+x3)/2;v2=(y2+y3)/2
        u3=(x3+x1)/2;v3=(y3+y1)/2
        
        
        trigraph([x1,u1,u3],[y1,v1,v3],n-1)  #开始递归
        trigraph([u1,x2,u2],[v1,y2,v2],n-1)
        trigraph([u3,u2,x3],[v3,v2,y3],n-1)
        
        
x=[0,300,150]
y=[300,300,0]
trigraph(x,y,7)
plt.show()

8.4 lambda函数

函数名=lambda 形参1,形参2...,形参n:表达式

8.4.1 求标准偏差

8.5 综合应用

8.5.1 二分法求根

 

9 列表

列表list:提供强大的处理功能:排序,索引、计数、切片等功能


9.1 列表函数


①    格式:del 列表
    
     Li=[ 1,20.9,-1] 
     del Li[1]
     print(Li)     # [1,-1]
    del Li          # 删除列表
    print(Li) # NameError: name 'Li' is not defined

 ②    枚举方式
     for item in L:
    下标索引方式
     用range函数配合
      for i in range(len(L)):
            对L[i]进行处理
    枚举加下标索引方式
    借助enumerate函数,其格式为:
     for i, item in enumerate(L):
      i是第i个元素的下标,item是值


③X=[1, 3, 23, 22, 45, 90]
y=x[:]  #整个表
和y=x
有什么区别?

x=[1, 3, 23, 22, 45, 90]
y=x[:]
x[1]=100
print(x,y)
z=x
x[2]=1000
print(x,z)
运行结果是什么?为什么?

/data/user/0/com.hipipal.qpy3/files/bin/qpython3-android5.sh  /storage/emulated/0/qpython/.last_tmp.py  && exit
/0/qpython/.last_tmp.py  && exit            <
[1, 100, 23, 22, 45, 90] [1, 3, 23, 22, 45, 90]
[1, 100, 1000, 22, 45, 90] [1, 100, 1000, 22, 45, 90]

#[QPython] Press enter to exit ...

9.2 列表对象方法


④    将列表排序
    格式:表.sort([reverse=True]),reverse缺省为False,升序,reverse =True,降序

⑤    将列表逆转
    格式:表.reverse()
L=[1,2,3,'laoyang']
L.reverse ()
print(L) 

⑥    将列表排序:里面只能全是数字或者全是字符串
    格式:表.sort([reverse=True]),reverse缺省为False,升序,reverse =True,降序

如果里面全是字符串,按照字符串比较大小的方式排序

⑦    对指定的元素计数,既元组在表中出现几次
    格式:表.count(元素)
L=['hellen','stery','antongni','hellen']
n=L.count('hellen')
print(n)
结果:2

⑧列表对象方法-pop
    将列表的指定位置元素返回,并将其从列表中删除,不指定位置,返回最后一个
    格式:表.pop([位置])
x=[4, 10, 1, 97, -5, -7]
n=x.pop()
print(n)
print(x)
print(x.pop(2))                 # 结果:1
print(x)        # 结果去掉1
# 所以对象pop会改变x的值

⑨自学其他
clear,remove,insert,extend


9.3 内置列表函数


⑩内建函数--zip
    zip函数将多个列表的对应元素整合为元组
    zip对象不能直接显示其包含的值,需要用list函数将zip对象转换为列表再显示
names=['张仟', '石戎',  '万行']
ages=[23, 21, 22]
ziped=zip(names,ages)
print(ziped)#显示存储位置
print(list(ziped))#zip必须有List

⑩①enumerate遍历
也要来List

⑩②filter
    filter(condition,list):根据指定条件,将符合条件的元素过滤出来,形成新列表。返回filter对象
    例【4-8】给定一组数,将其中的偶数组成新列表

⑩③map

map(函数,列表)
map必须外套list才能显示出来,如果无list显示位置ID

⑩④zip

zip函数将多个列表的对应元素整合为元组

zip对象不能直接显示其包含的值,需要用list函数将zip对象转换为列表再显示

 

9.4 列表推导式

注意:大的列表要把所有循环都括进去,for前面的空格可以省略

9.4.1 二维列表(矩阵)

索引:x=[[1,2,3],[5,4,6]]

>>>x[1][2]=6

矩阵相乘***

A=[[1, 3,4],[5,1.0,0]]
B=[[3,1,5],[7,0,2],[2, -1, 3]]
C=[ ]  #结果矩阵
row=len(A)   # 取A矩阵的行数
col=len(B[0])  # 取B矩阵的列数
for i in range(row):
    oneRow=col*[None]  # 结果矩阵的一行
    for j in range(col):
        s=0.0
        for k in range(len(B)):  #计算结果矩阵的第i行第j列元素
            s += A[i][k]*B[k][j]
        oneRow[j]=s
    C.append(oneRow)
print(C)

>>>
[[32.0, -3.0, 23.0], [22.0, 5.0, 27.0]]

9.4.2 九宫格

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值