Python下的内置函数,字符串及列表(解释器为python3.6)

一.Python下的内置函数

<1>min函数:求取多个数中最小值(至少两个数)

print(min (3,4,1))         #输出1

<2>max函数:求取多个数中的最大值(至少两个数)

print(max (3,4,1))        #输出4

<3>cmp函数:比较两个值的大小——>只适用于python2

相等(返回0);小于(返回-1);大于(返回1)

<4>sum函数:对容器中的元素求和

<1>range:实际上是列表

print(sum(range(1,101)))       #输出5050
print(sum(range(1,101,2)))    #输出2500
print(sum(range(2,101,2)))    #输出2550

<2>列表

print(sum([1,2,3,4,5]))       #输出15

<3>元组
print(sum((1,2,3,4,5)))       #输出15

<4>set集合
print(sum({1,2,3,4,5}))       #输出15

<5>字典:默认是对键值求和
print(sum({1:'name',20:'age'}))       #输出21

<5>pow函数:计算幂次方

print(pow(2,3))          #输出8,表示2的3次方

<6>abs函数:计算某个数的绝对值

print(abs(-20))           #输出20

<7>len函数:计算字符串或容器中的元素个数

(1)字符串

print(len('abc'))                                 #输出3

(2)列表
print(len([1,2,3,3,2,1]))                     #输出6

(3)元组
print(len((1,2,3,3,2,1)))                    #输出6

(4)set集合
print(len({1,2,3}))                              #输出3

(5)字典
print(len({'name':'xin','age':24}))     #输出2

<8>del函数:删除变量或字符串或容器(列表,元组,set集合,字典)

(1)删除变量

a=1
print(a)      #输出1zic()1()1
del  a
print(a)      #报错: NameError: name 'a' is not defined

(2)删除字符串,不支持后面接下标位或切片——>因为字符串是不可变类型

a=1
print(a)      #输出1
del  a
print(a)      #报错: NameError: name 'a' is not defined

(3)删除列表

l=['2','3','hello','world','python']
print(l)              #输出['2', '3', 'hello', 'world', 'python']
del  l[1]
print(l)              #输出['2', 'hello', 'world', 'python']
del  l[1:3]
print(l)              #输出['2', 'python']
del  l
print(l)              #报错NameError: name 'l' is not defined

(4)删除元组,不支持后面接下标位或切片——>因为字符串是不可变类型

s=('2','3','hello','world','python')
print(s)              #输出('2', '3', 'hello', 'world', 'python')
del  s
print(s)              #报错NameError: name 's' is not defined

(5)删除set集合,不支持后面接下标位或切片——>虽然set集合是可变类型,但是set集合是无序的,所以不支持下标索引和切片

s={'2','3','hello','world','python'}
print(s)              #输出{'hello', '3', '2', 'world', 'python'}
del  s
print(s)              #报错NameError: name 's' is not defined

(6)删除字典,不支持后面接下标位或切片,——>虽然字典是可变类型,但是字典是无序的,所以不支持下标索引和切片。但支持后面接要删除的键的名称

d={'name':'xin','age':24,'home':'linfen','score':90}
print(d)                   #输出{'name': 'xin', 'age': 24, 'home': 'linfen', 'score': 90}
del  d['name']         #输出{'age': 24, 'home': 'linfen', 'score': 90}
print(d)
del  d
print(d)                    #报错NameError: name 'd' is not defined

<9>enumerate函数:枚举(返回索引值和对应的value值)。适用于字符串和容器

(1)字符串

for i,v in enumerate('hello'):
    print(i, v)
#输出 0 h
#        1 e
#        2 l
#        3 l
#        4 o

(2)列表

for i,v in enumerate(['hello','world',3]):
    print(i, v)
# 输出  0 hello
#          1 world
#          2 3

(3)元组

for i,v in enumerate(('hello','world',3)):
    print(i, v)
# 输出  0 hello
#          1 world
#          2 3

(4)set集合

值的注意的是:set集合是无序的,所以在将两个setr集合中对应的元素放到一个元组中时,可能会乱序

for i,v in enumerate({'hello','world',3}):
    print(i, v)
# 输出  0 3
#          1 world
#          2 hello

(5)字典——>返回的是键对应的值

for i,v in enumerate({'name':'xin','age':24,'home':'linfen'}):
    print(i, v)
# 输出  0 name
#           1 age

#           2 home

<10>zip函数:将两个字符串或容器对应的元素放到一个元组中——>取短不取长

或者将两个字符串或容器中的元素之间一一对应

(1)字符串

 

 

(2)列表

 

(3)元组

 

(4)set集合

值的注意的是:set集合是无序的,所以在将两个setr集合中对应的元素放到一个元组中时,可能会乱序

 

(5)字典——>返回的是键对应的值

 

二.Python下的字符串——不可变类型

1.字符串的定义方法

a='hello'
b='what\'s up'            #其中的'需要转义
c="what's up"

print(a)    #输出hello
print(b)    #输出what's up
print(c)    #输出what's up


2.求取字符串的长度——len函数

s='hello'
l=len(s)
print(l)      #输出为5


3.字符串的索引:从左往右数为:0,1,2...;从右往左数:...-2,-1(当下标索引超出范围时,会报错)

s='hello'
print(s[0])   #打印索引为0的字符,输出h
print(s[1])   #打印索引为1的字符,输出e
print(s[-1])  #打印索引为-1的字符,输出o


4.字符串的切片(对字符串进行截取)

语法规则:string[起始:结束:步长]。
值得注意的是:

  1. 起始,结束和步长都可以损裂。起始损裂时,默认为0;结束损裂时,默认到最后一个字符(即len(string));步长损裂时,默认为1;
  2. 但是值得注意的是:当步长<0时,起始损裂时,默认是-1,而非0;结束损裂时,默认是-len(string)-1,而非len(string)。
    所以string[::-1]相当于 string[-1:-len(string)-1:-1],也就是从最后一个元素到第一个元素复制一遍,即倒序。
  3. 包头不包尾(不包括结束值本身)

s='hello'
print(s[0:4:2])                    #打印索引为0,2的字符,输出hl
print(s[0:3])                       #打印索引为0,1,2的字符,输出hel。这里损裂了步长。值得注意的是,当步长损裂时,步长默认为1。
print(s[:3])                         #打印索引为0,1,2的字符,输出hel。这里损裂了起始和步长。值得注意的是,当起始损裂时,起始默认是0。
print(s[1:])                         #打印索引为1,一直到最后一个字符,输出ello。这里损裂了终止和步长。值得注意的是,当终止损裂时,默认是到最后一个字符。
print(s[:-1])                        #打印起始到索引为-2的字符,输出hell。这里损裂了起始和步长。

print(s[:])或print(s[::])         #打印整个字符串s,输出hello。这里损裂了起始、终止和步长。

print(s[::-1])                       #反转整个字符串s,输出olleh。这里损裂了起始、终止。

print(s[:-1:-1])                    #打印出来为空。这里损裂了起始(因为步长为-1,所以起始默认为-1)。

print(s[0:-1:-1])                  #打印出来为空。因为这里步长为负数,所以相当于字符串的索引从右往左数,因为从右往左数是-1,-2,-3...,而没有0,所以这里输出为空。


5.字符串的切片的应用+for循环(迭代)
<1>打印字符串的两种方法

(1)利用字符串的切片
s='hello'
print(s[:])或print(s[::])      #打印全部字符,输出hello。这里损裂了起始,步长和终止。
(2)
s='hello'
print(s)         #打印全部字符,输出hello。

<2>字符串反转的三种方法

(1)利用字符串的切片
s='hello'
print(s[::-1])      #字符串反转,输出olleh。这里损裂了起始,终止,步长为-1。

(2)利用while循环
s='hello'
l=len(s)-1
while l>=0:
    print(s[l])      #换行输出,输出olleh。
    #print(s[l],end='')     #不换行输出,输出olleh
    l-=1

(3)利用for循环
利用for循环有两种方法

<1>利用len函数
s='hello'
l=len(s)
for i in range(l-1,-1,-1):
    print(s[i])       #换行输出,输出olleh。
    #print(s[i],end='')  #不换行输出,输出olleh。

<2>利用字符串的遍历
s='hello'
for i in s[::-1]:
    print(i)           #换行输出,输出olleh。
    #print(i,end='')      #不换行输出,输出olleh。


6.字符串的运算——只局限于同类型(同样是字符串)
<1>加法运算——字符串的连接

s='hello'
print(s+'world')           #输出helloworld

<2>乘法运算(只限于字符串与整数相乘)——字符串的重复    

s='hello'
print(s*5)               #输出hellohellohellohellohello


7.字符串的成员操作符——in,not in。返回结果为True或False

s='hello'
print('h' in s)            #判断h是否在s这个字符串中,输出True
print('h' not in s)      #判断h是否不在s这个字符串中,输出False


8.字符串的常见的函数操作
<1>isalpha函数——判断字符串的组成成分,全是字母,返回True,否则返回False

print('123'.isalpha())     #输出False
print('hello'.isalpha())    #输出True

<2>isdigit函数——判断字符串的组成成分,全是数字,返回True,否则返回False

print('123'.isdigit())            #输出True
print('123abc'.isdigit())      #输出False

<3>isalnum函数——判断字符串的组成成分,全是数字或字母,返回True,否则返回False

print('123abc'.isalnum())    #输出True

<4>istitle函数——判断字符串的组成成分,如果只有首字母大写,其余字母全小写,返回True,否则返回False

print('Hello'.istitle())       #输出True
print('HeLlo'.istitle())     #输出False

<5>islower函数——判断字符串的组成成分,如果字母全小写,返回True,否则返回False

print('hELLO'.islower())     #输出False
print('hello'.islower())         #输出True

<6>isupper函数——判断字符串的组成成分,如果字母全大写,返回True,否则返回False

print('hELLO'.isupper())     #输出False
print('HELLO'.isupper())     #输出True

<7>lower函数——将字符串的所有字母都改为小写。

print('heLLo'.lower())       #输出hello

<8>upper函数——将字符串的所有字母都改为大写。

print('heLLo'.upper())       #输出HELLO

<9>startswith函数——判断字符串是否以什么开头。

print('hello.log'.startswith('hello'))     #输出True

<10>endswith函数——判断字符串是否以什么结尾。

print('hello.log'.endswith('hello'))     #输出False

<11>strip函数——去掉字符串中两边的指定的字符值得注意的是,如果不加,默认是空格。
(1)去掉空格(这里的空格是广义的空格)

s='  hello  '
print(s)
print(s.strip())      #去掉字符串s中的左右两边的空格

print(s.lstrip())     #去掉字符串s中的左边的空格

print(s.rstrip())     #去掉字符串s中的右边的空格

值得注意的是,这里的空格是广义的空格,(也包含换行符和制表符)

s='\nhello\t\t'
print(s)
print(s.strip())      #去掉字符串s中的左右两边的空格
print(s.lstrip())     #去掉字符串s中的左边的空格
print(s.rstrip())     #去掉字符串s中的右边的空格

(2)去掉指定的字符

s='hellhelh'
print(s.strip('h'))     #去掉字符串s中的两边的'h',输出ellhel
print(s.lstrip('h'))    #去掉字符串s中的左边的'h',输出ellhelh
print(s.rstrip('h'))    #去掉字符串s中的右边的'h',输出hellhel

<12>查找字符串中指定的字符——find函数和index函数。两者的区别,在于找不到字符时的返回值(find返回-1;index会报错)
(1)find函数和rfind函数——查找字符串中是否包含指定的字符。
值得注意的是,默认从左边开始找,找到,返回第一个字符所在的索引,找不到,返回-1。find函数默认是从左到右的第一个,想要找从右到左的第一个,则用rfind函数。

s='hello world hello'
print(s.find('hello'))     #查找hello是否在s字符串中,如果在,则返回第一个字符所在的索引。输出0
print(s.find('java'))      #查找java是否在s字符串中,如果不在,则返回-1。输出-1
print(s.rfind('hello'))    #从右开始找,查找hello是否在s字符串中,如果在,则返回第一个字符所在的索引。输出12

(2)index函数和rindex函数——查找字符串中是否包含指定的字符。
值得注意的是,默认从左边开始找,找到,返回第一个字符所在的索引,找不到,会报错。index函数默认是从左到右的第一个,想要找从右到左的第一个,则用rindex函数。

s='hello world hello'
print(s.index('hello'))      #查找hello是否在s字符串中,如果在,则返回第一个字符所在的索引。输出0
print(s.index('java'))       #查找java是否在s字符串中,如果不在,则报错。输出报错
print(s.rindex('hello'))     #从右开始找,查找hello是否在s字符串中,如果在,则返回第一个字符所在的索引。输出12

<13>replace函数——将字符串中的某些字符替换为别的字符。

replace函数如果不写替换次数,则默认全部替换

s='hello world hello'
print(s.replace('hello','java'))      #将字符串s中所有的hello替换为java
print(s.replace('hello','java',1))   #将字符串s中的出现的第一个hello替换为java。参数1表示替换1次(从左边数)
print(s.replace('hello','java',2))   #将字符串s中的出现的两个hello替换为java。参数2表示替换2次(从左边数)

<14>center函数——将输出的字符串,居中。默认用空格补全。

print('学生管理系统'.center(30))        #居中输出,默认用空格补全。
print('学生管理系统'.center(30,'*'))     #居中输出,用'*'补全。

<15>ljust函数——将字符串左对齐输出。

print('学生管理系统'.ljust(30))           #左对齐输出,默认用空格补全。
print('学生管理系统'.ljust(30,'*'))       #左对齐输出,用'*'补全。

<16>rjust函数——将字符串右对齐输出。

print('学生管理系统'.rjust(30))            #右对齐输出,默认用空格补全。
print('学生管理系统'.rjust(30,'*'))        #右对齐输出,用'*'补全。

<17>count函数——统计一个字符串中某个字符出现的次数。

print('hello'.count('l'))        #输出为2
print('hello'.count('ll'))       #输出为1

<18>split函数——按照某个分隔符进行分隔,分隔之后是一个由字符串组成的列表。maxsplit,表示最大分割成几段。

要注意的是:

(1)split函数分隔开之后,是一个列表

(2)经过split函数分隔之后,结果当中不出现分隔符

(3)split函数不加分隔符的话,默认是以所有的符号(比如空格、制表符\t、换行符\n等。)为分隔符

s='hello world    java'
print(s.split())             #输出为['hello', 'world', 'java']

s='172.25.254.183'
print(s.split('.'))           #输出为['172', '25', '254', '183']

s='hello world bjsxt laoxiao is bjsxt.com'
print(s.split('  ',2))        #输出为['hello', 'world', 'bjsxt laoxiao is bjsxt.com']。其中2表示分为3段,即最大编号为2

s='hello world bjsxt laoxiao is bjsxt.com'

print(s.split('laoxiao'))   #输出为['hello world bjsxt' ,  'is bjsxt.com']。输出结果中不含有laoxiao

<19>splitlines函数——不用指定分隔符,默认分隔符为换行符

 

<20>partition函数和rpartition函数——字符串的分割输出。

要注意的是:

(1)partition函数与split函数不同的是:split函数分隔开之后,是一个列表。而partition函数分隔开之后,是一个元组

(2)partition函数与split函数不同的是:split函数使用分隔符之后,结果中不会出现分隔符。而partition函数使用分隔符之后,结果中会出现分隔符

(3)partition函数与split函数不同的是:split函数不加分隔符时,默认分隔符是空格。而partition函数不加分隔符时,会报错

(4)partition函数与split函数不同的是:split函数使用分隔符之后,能分成几段就分成几段。而partition函数使用分隔符之后,默认分成3段。

(5)partition函数与split函数不同的是:split函数可以指定分隔的段数。而partition函数不能指定分隔的段数。

(6)rpartition函数与partition函数的用法相同,只是rpartition是从右边开始。

str='hello world bjsxt laoxiao is bjsxt.com'
print(str.partition('laoxiao'))          #输出为('hello world bjsxt ', 'laoxiao', ' is bjsxt.com')

str='hello world bjsxt laoxiao is bjsxt.com'

print(str.partition(' '))                    #输出为('hello', ' ', 'world bjsxt laoxiao is bjsxt.com')

print(str.rpartition(' '))                   #输出为('hello world bjsxt laoxiao is', ' ', 'bjsxt.com')

<21>join函数——将某些字符以某些符号连接起来。其实是用来将容器(列表,元组,set集合,字典)转换成字符串的

date='2019-01-15'
print(date.split('-'))                   #输出为['2019', '01', '15']
print(''.join(date.split('-')))        #输出为20190115
print('/'.join(date.split('-')))       #输出为2019/01/15

<22>capitalize函数——将字符串的第一个单词的首字母大写。

print('hello'.capitalize())     #输出为Hello

<23>isspace函数——判断字符串的组成成分,如果全是空格,返回True,否则返回False。

print(''.isspace())         #输出为False
print('   '.isspace())      #输出为True

<24>title函数——把字符串的每个单词的首字母大写。

print('hello world'.title())     #输出Hello World

9.如何快速生成验证码,内推码??

<1>生成验证码内推码的格式:

import string

code_str=string.ascii_letters+string.digits
print(code_str)
#输出abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

<2>生成验证码,内推码练习:

生成1000个随机的四位验证码

import string
import random

code_str=string.ascii_letters+string.digits

def gen_code(len=4):
    return   '.join(random.sample(code_str,len))

gen_code()                                                              #生成四位随机的验证码

print([gen_code()   for   i   in range(1000)])                #生成1000个四位随机的验证码

三.Python下的字符串练习

1.字符串之回文数的判断(回文数就是字符串和字符串的反转相同)

示例 1:
        输入: 121
        输出: true
示例 2:
        输入: -121
        输出: false
        解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因>此它不是一个回文数。
示例 3:
        输入: 10
        输出: false
        解释: 从右向左读, 为 01 。因此它不是一个回文数。

num=input('请输入一个数字:')
if num==num[::-1]:
    print('这个数字%s是回文数' %num)
else:
    print('这个数字%s不是回文数' %num)

2.字符串之判断变量名是否合法

变量名是否合法:
 1.变量名可以由字母,数字或者下划线组成
 2.变量名只能以字母或者下划线开头
s = 'hello@'

1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]

#1.变量名的第一个字符是否为字母或下划线
#2.如果是,继续判断 --> 4
#3.如果不是,报错
#4.依次判断除了第一个字符之外的其他字符
#5.判断是否为字母数字或者下划线

while True:
    str=input('请输入一个变量名:')
    if str[0].isdigit():
        print('变量名%s以数字开头,该变量名非法' %str)
    elif str=='exit':
        print('退出')
        break
    else:
        for i in str[1:]:
            if i.isalnum() or i=='_':
                pass
            else:
                print('变量名%s非法' %str)
                break
        else:
            print('变量名%s合法' % str)

3.字符串之判断出勤率

给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),
那么这个学生会被奖赏。
你需要根据这个学生的出勤纪录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False

"""

str=input('请输入出勤记录(A:缺勤;L:迟到;P:到场):')
print(str.count('A')<=1 and str.count('LLL')==0)

4.字符串之句子反转

(2017-小米-句子反转)
- 题目描述:
> 给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。

- 示例1:
- 输入
    hello xiao mi
- 输出
    mi xiao hello

str=input('请输入一个英文句子:')
print(' '.join(str.split()[::-1]))

5.字符串之删除字符

- 题目描述:
输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。

例如,输入”They are students.”和”aeiou”,
则删除之后的第一个字符串变成”Thy r stdnts.”
- 输入描述:
每个测试输入包含2个字符串
- 输出描述:
输出删除后的字符串
- 示例1:
输入
    They are students.
    aeiou
输出
    Thy r stdnts.

#方法一:
str1=input('请输入第一个字符串:')
str2=input('请输入第二个字符串:')
for i in str1:
    if i not in str2:
        print(i,end='')

#方法二:
str1=input('请输入第一个字符串:')
str2=input('请输入第二个字符串:')
for i in str1:
    if i in str2:
        str1=str1.replace(i,'')
print(str1)

#方法三:
st1=input()
st2=input()
print(''.join([i for i in st1 if i not in st2]))

6.字符串之小学生算术测试系统

小学生算术能力测试系统:
设计一个程序,用来实现帮助小学生进行百以内的算术练习,它具有以下功能:
提供10道加、减、乘或除四种基本算术运算的题目;
练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否
正确并显示出相应的信息。

import random

op = ['+', '-', '*', '/']
count = 1
right = 0
while count <= 10:
    # 输入参与运算的两个数字
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)
    symbol = random.choice(op)
    print('%s%s%s' % (num1, symbol, num2))
    # 运算符为加法时执行的程序
    if symbol == '+':
        question = input('请输入你的答案:')
        result = str(num1 + num2)
        # 判断答案是否正确
        if question == result:
            print('回答正确')
            right += 1
        elif question == 'q':
            break
        else:
            print('回答错误')
    elif symbol == '-':
        question = input('请输入你的答案:')
        result = str(num1 - num2)
        # 判断答案是否正确
        if question == result:
            print('回答正确')
            right += 1
        elif question == 'q':
            break
        else:
            print('回答错误')
    elif symbol == '*':
        question = input('请输入你的答案:')
        result = str(num1 * num2)
        # 判断答案是否正确
        if question == result:
            print('回答正确')
            right += 1
        elif question == 'q':
            break
        else:
            print('回答错误')
    elif symbol == '/':
        if num2 == 0:
            print('请输入非0的数字')
        else:
            question = input('请输入你的答案:')
            result = str(num1 / num2)
            # 判断答案是否正确
            if question == result:
                print('回答正确')
                right += 1
            elif question == 'q':
                break
            else:
                print('回答错误')
    count += 1
percent = right / count
print('测试结束,共回答%d道题,正确个数为%d,正确率为%.2f%%' % (count - 1, right, percent * 100))

四.Python下的列表(list)——可变类型

1.Python的内置的一种数据类型是列表:list

list是一种有序的集合(集合包括列表——list;元组——tuple;set集合——set;字典——dict)。可以随时添加和删除其中的元素。且,元素可以重复。元素可以是任意类型的数据。

2.列表(list)同字符串一样也有len函数。

3.列表(list)同字符串一样也有下标索引。(正着从0开始,倒着从-1开始)。超出索引时,回报错。

4.列表(list)同字符串一样也有切片。

5.列表(list)同字符串一样也有计算(加法和乘法——乘法只限于列表与数字相乘)。——只局限于同类型(同是列表)

6.列表(list)同字符串一样也有成员运算符。

7.列表(list)同字符串一样也支持for循环。

8.列表(list)的定义方法:

names=[100,'200',True,2.3,[100,200,'300']]           #列表中的元素可以是任意类型,当然也包括列表,元组,set集合,字典。

如何定义一个空列表呢?

l=[]                                    #定义一个空列表

print(l)             #输出[]
print(type(l))   #输出<class 'list'>

l=list()                              #定义一个空列表
print(l)                  #输出[]
print(type(l))        #输出<class 'list'>

值的注意的是:当列表中嵌套列表,元组,set集合,字典,字符串——>有下标索引时,列表的索引和切片的写法:即[]是可以多个出现的,只要有索引这个属性就行。

service=[['http',80],['ssh',22],'hello',('ftp',21)]
print(service[1][1])          #输出22
print(service[-1][1])         #输出21
print(service[:][1])            #输出['ssh', 22],同service[1]
print(service[:-1][0])        #输出['http', 80]                         

9.列表(list)的相关操作(增删改查)

<1>增(append,extend,insert)

(1)append:通过append可以相列表中添加一个元素(只能在列表的最后面追加)

service=['http','ssh','ftp']
service.append('firewalld')
print(service)          #输出['http', 'ssh', 'ftp', 'firewalld']

(2)extend:通过extend可以将另一个集合中的元素一一逐一添加到列表中

service=['http','ssh','ftp']
service.extend(['hello','firewalld'])
print(service)         #输出['http', 'ssh', 'ftp', 'hello', 'firewalld']

(3)insert:insert可以在任意位置添加一个元素

service=['http','ssh','ftp']
service.insert(1,['hello','firewalld'])
print(service)         #输出['http', ['hello', 'firewalld'], 'ssh', 'ftp']

<2>删(pop,remove,del)

(1)pop:默认取列表中的最后一个元素进行删除,并且将该元素值返回。也可以指定索引删除指定索引处的元素值

service=['http','ssh','ftp']
service.pop()
print(service)         #输出['http', 'ssh']

service=['http','ssh','ftp']
a=service.pop(0)
print(service)         #输出['ssh', 'ftp']
print(a)                   #输出http

(2)del:可以删除列表中某个下标位或切片对应的元素,也可以删除整个列表——>不仅仅适用于列表,也适用于字符串,元组,set集合和字典。

service=['http','ssh','ftp']
del service[:2]
print(service)         #输出['ftp']

service=['http','ssh','ftp']
del service[2]
print(service)         #输出['http', 'ssh']

service=['http','ssh','ftp']
del service
print(service)         #输出报错(service找不到)

(3)remove:类似于del,但其中要接的是删除的一个元素

service=['http','ssh','ftp']
service.remove('http')
print(service)         #输出['ssh', 'ftp']

<3>改:利用列表中的下标位或者索引来修改一些元素。

service=['http','ssh','ftp']
service[2]='firewalld'
print(service)         #输出['http', 'ssh', 'firewalld']

 

service=['http','ssh','ftp']
service[:2]=['firealld','samba']
print(service)         #输出['firealld', 'samba', 'ftp']

<4>查(not in,in,count,index)

(1)not  in:不在,返回True;在,返回False——>成员操作符

service=['http','ssh','ftp']
print('http' not in service)         #输出False

(2)in:在,返回True;不在,返回False——>成员操作符

service=['http','ssh','ftp']
print('http' in service)         #输出True

(3)count:返回某个元素的下标位

service=['http','ssh','ftp','http']
print(service.count('http'))         #输出2

(4)index:统计某个元素出现的次数,默认统计一个,并且从左往右数

service=['http','ssh','ftp','http']
print(service.index('http'))         #输出0,默认统计一个,并且从左往右数
print(service.index('ssh'))          #输出1

10.列表(list)中的排序函数——>sort()方法,sorted函数和reverse函数

<1>sort()方法:默认升序排列。要使用sort函数,必须保证列表中的元素是同类型的。

1.

service=['alice','bob','harry','Bob']
service.sort()
print(service)         #输出['Bob', 'alice', 'bob', 'harry']。字母按照ASCII码进行排序。

2.

service=['alice','bob','harry','Bob']
service.sort(key=str.lower)

print(service)          #输出['alice', 'bob', 'Bob', 'harry']

 

service=['alice','bob','harry','Bob']
service.sort(key=str.upper)
print(service)          #输出['alice', 'bob', 'Bob', 'harry']

3.key后面也可以是个有返回值的函数名。如sorted函数和sort()方法练习一:

4.

service=['alice','bob','harry','Bob']
service.sort(reverse=True)           #逆序排序
print(service)         #输出['harry', 'bob', 'alice', 'Bob'

<2>sorted函数:默认升序排列,要使用sorted函数,必须保证列表中的元素是同类型的。

值的注意的是,此函数不改变原来的列表。

1.

service=['alice','bob','harry','Bob']
print(sorted(service))    #输出['Bob', 'alice', 'bob', 'harry']。字母按照ASCII码进行排序。
print(service)                 #输出['alice', 'bob', 'harry', 'Bob']

2.

service=['alice','bob','harry','Bob']
print(sorted(service,reverse=True))    #输出['harry', 'bob', 'alice', 'Bob']。字母按照ASCII码进行排序。#匿名排序
print(service)                 #输出['alice', 'bob', 'harry', 'Bob']

3.也可以接key,key后面也可以是个有返回值的函数名。如sorted函数和sort()方法练习一

sorted函数和sort()方法练习一:

#1.
li=[('bpple1',20,3.2),('apple2',1000,3.1),('apple1',20,3.0)]
#默认是以列表中的元组的第一个元素进行排序
#方法一:使用sorted函数
print(sorted(li))
#输出[('apple1', 20, 3.0), ('apple2', 1000, 3.1), ('bpple1', 20, 3.2)]
#方法二:使用列表的sort()方法
li.sort()
print(li)


#2.
li=[('bpple1',20,3.2),('apple2',1000,3.1),('apple1',20,3.0)]
#想要按照列表中的元组的第二个元素进行排序,该怎么办呢?

def two_sorted(x):
    return x[1]
#方法一:使用sorted函数
print(sorted(li,key=two_sorted))
#输出[('bpple1', 20, 3.2), ('apple1', 20, 3.0), ('apple2', 1000, 3.1)]
#方法二:使用列表的sort()函数
li.sort(key=two_sorted)
print(li)

 

#3.
#想要按照列表中的元组的第三个元素进行排序,该怎么办呢?
def three_sorted(x):
    return x[2]
#方法一:使用sorted函数
print(sorted(li,key=three_sorted))
#输出[('apple1', 20, 3.0), ('apple2', 1000, 3.1), ('bpple1', 20, 3.2)]
#方法二:使用列表的sort()函数
li.sort(key=three_sorted)
print(li)


#4.
#如果列表中元组的第二个元素相同,那么按照元组的第三个元素进行排序,该怎么办呢?
def two_three_sorted(x):
    return x[1],x[2]
#方法一:使用sorted函数
print(sorted(li,key=two_three_sorted))
#输出[('apple1', 20, 3.0), ('apple2', 1000, 3.1), ('bpple1', 20, 3.2)]
#方法二:使用列表的sort()函数
li.sort(key=two_three_sorted)
print(li)        

sorted函数和sort()方法练习二:

 (2018-携程-春招题)题目需求:
给定一个整型数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
# 输入:
    第一行是数组长度, 后续每一行是数组的一条记录;
    4
    0
    7
    0
    2
# 输出:
    调整后数组的内容;
    4
    7
    2
    0
    0
"""

#方法一:
l=[]
length=int(input())
for i in range(length):
    segment=input()
    l.append(segment)
def l_sorted(x):
    if x=='0':
        return 1
    return 0
print(length)
for j in sorted(l,key=l_sorted):
    print(j)


#方法二:
def zero_if(l):
    for n in l:
        if n=='0':
            return 1
        else:
            return 0
len=int(input())
li=[input() for i in range(len)]
print(len)
for j in sorted(li,key=zero_if):
    print(j)


#方法三:
l=[]
length=int(input())
for i in range(length):
    segment=input()
    l.append(segment)
def l_sorted(x):
    return x=='0'
print(length)
for j in sorted(l,key=l_sorted):
    print(j)

<3>reverse函数:将列表倒置

方法一:使用reverse函数

service=['alice','bob','harry','Bob',1]
service.reverse()
print(service)         #输出[1, 'Bob', 'harry', 'bob', 'alice']

方法二:使用切片

service=['alice','bob','harry','Bob',1]
print(service[::-1])         #输出[1, 'Bob', 'harry', 'bob', 'alice']

要注意的是:方法一和方法二的区别在于——方法一将service这个列表本身修改了,而方法二service这个列表本身并没有修改

11.random模块中的shuffle函数:将列表的顺序随机打乱。

import random
service=['alice','bob','harry','Bob',1]
random.shuffle(service)
print(service)         #第一次输出['Bob', 'bob', 'alice', 'harry', 1],第二次输出['bob', 1, 'alice', 'Bob', 'harry']

五.Python下的列表练习

1.列表之判断季节

用户输入月份,判断这个月是哪个季节

month=input('请输入月份(1-12):')
if month in ['3','4','5']:
    print('春季')
elif month in ['6','7','8']:
    print('夏季')
elif month in ['9','10','11']:
    print('秋季')
elif month in ['12','1','2']:
    print('冬季')
else:
    print('请输入正确的月份')

2.列表之用户登陆

1.系统里面有多个用户,用户的信息目前保存在列表里面
    users = ['root','westos']
    passwd = ['123','456']
2.用户登陆(判断用户登陆是否成功
    1).判断用户是否存在
    2).如果存在
        1).判断用户密码是否正确
        如果正确,登陆成功,推出循环
        如果密码不正确,重新登陆,总共有三次机会登陆
    3).如果用户不存在
    重新登陆,总共有三次机会

users=['root','westos']
passwd=['123','456']
i=0
j=0
while i<3 and j<3:
    inuser=input('请输入要登陆的用户名:')
    #判断,用户不存在时,做的事情
    if inuser not in users:
        print('用户不存在,请重新输入用户名')
        i+=1
    #判断用户存在时,输入密码
    else:
        inpasswd=input('请输入密码:')
        user_index=users.index(inuser)
        passwd_index=passwd.index(inpasswd)
        if user_index==passwd_index:
            print('登陆成功')
            break
        else:
            print('密码输入错误,请重新输入密码')
            j+=1

3.列表之后台管理员管理会员信息

# 1. 后台管理员只有一个用户: admin, 密码: admin。尝试次数为3。
# 2. 当管理员登陆成功后, 可以管理前台会员信息.
# 3. 会员信息管理包含:
#       添加会员信息
#       删除会员信息
#       查看会员信息
#       退出
 - 添加用户:
    1). 判断用户是否存在?
    2).  如果存在, 报错;
    3).  如果不存在,添加用户名和密码分别到列表中;

- 删除用户
    1). 判断用户名是否存在
    2). 如果存在,删除;
    3). 如果不存在, 报错;

i=0
#定义两个空列表,一个用来存放会员名,另一个用来存放密码
user_list=[]
passwd_list=[]
while i<3:
    user=input('请输入管理员名:')
    passwd=input('请输入密码:')
    if not (user=='admin' and passwd=='admin'):
        print('登陆失败,请重试,还有%s次机会' %(2-i))
    else:
        print('登陆成功')
        while True:
            print('''
              操作目录
            1) 添加会员信息
            2) 删除会员信息
            3) 查看会员信息
            4) 退出
            ''')
            action=input('请输入你要执行的操作:')
            if action=='1':
               print('添加会员'.center(30,'*'))
               add_user=input('请输入你要添加的会员名:')
               if add_user in user_list :
                   print('%s会员已经存在,不需要再次添加' %add_user)
               else:
                   add_passwd=input('请输入会员名对应的密码:')
                   user_list.append(add_user)
                   passwd_list.append(add_passwd)
                   print(user_list)
                   print(passwd_list)
                   print('%s添加成功' %add_user)
            elif action=='2':
                print('删除会员'.center(30, '*'))
                del_user = input('请输入你要删除的会员名:')
                if del_user not in user_list:
                    print('%s会员不存在,不能删除' %del_user)
                else:
                    user_index=user_list.index(del_user)
                    user_list.pop(user_index)
                    passwd_list.pop(user_index)
                    print(user_list)
                    print(passwd_list)
                    print('%s删除成功' %del_user)
            elif action=='3':
                print('\t会员名\t密码')
                length=len(user_list)
                for j in range(length):
                    print('\t%s\t%s' %(user_list[j],passwd_list[j]))
            elif action=='4':
                print('bye...')
                exit()
            else:
                print('请输入正确的操作对应的数字')
        break
    i+=1

4.列表实现栈的工作原理

栈的工作原理
    入栈
    出栈
    查看栈顶元素
    栈的长度
    栈是否为空

#定义一个空列表,用来存放栈的元素
l=[]
while True:
    print('''
       操作目录
     1) 入栈
     2) 出栈
     3) 查看栈顶元素
     4) 栈的长度
     5) 栈是否为空
     6) 退出
    ''')
    action=input('请输入你的选择:')
    if action=='1':
        print('入栈'.center(30,'*'))
        push=input('请输入要入栈的元素:')
        l.append(push)
        print(l)
        print('%s元素入栈成功' %push)
    elif action=='2':
        print('出栈'.center(30, '*'))
        if not l:
            print('栈为空,不能出栈')
        else:
            l.pop(-1)
            print(l)
            print('%s出栈成功')
    elif action=='3':
        print('查看栈顶元素'.center(30, '*'))
        if l:
            print('栈顶元素为%s' %l[-1])
        else:
            print('栈顶元素不存在')
    elif action=='4':
        print('查看栈的长度'.center(30, '*'))
        print('栈的长度为:%s' %(len(l)))
    elif action=='5':
        print('查看栈是否为空'.center(30, '*'))
        if len(l)==0:
            print('栈为空')
        else:
            print('栈不为空')
    elif action=='6':
        exit()
    else:
        print('请输入正确的选择')

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值