欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

列表、元组、字符串

程序员文章站 2022-07-14 22:17:54
...

一、列表
整型<class ‘int’>
浮点型<class ‘float’>
布尔型 <class ‘bool’>
列表 <class ‘list’>
元组 <class ‘tuple’>
字典 <clss ‘dict’>
集合 <class ‘set’>
字符串 <class ‘str’>

#列表是有序集合,没有固定大小,能够保存任意数量任意类型的python对象,语法为[元素1,元素2,……,元素n] 中括号和逗号

例子:

x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
print(x,type(x))

x = [2,3,4,5,6,7]
print(x,type(x))
#['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>
#[2, 3, 4, 5, 6, 7] <class 'list'>

1.利用range创建列表

x = list(range(10))
print(x,type(x))

x = list(range(1,11,2))
print(x,type(x))

x = list(range(10,1,-2))
print(x,type(x))
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
#[1, 3, 5, 7, 9] <class 'list'>
#[10, 8, 6, 4, 2] <class 'list'>

  1. 利用推导式创建列表
x = [0]*5
print(x,type(x))

x = [0 for i in range(5)]
print(x,type(x))

x = [i for i in range(10)]
print(x,type(x))

x = [i for i in range(1,10,2)]
print(x,type(x))

x = [i for i in range(10,1,-2)]
print(x,type(x))

x = [i **2 for i in range(1,10)]
print(x,type(x))

x = [i for i in range(100) if (i%2) != 0 and (i%3) ==0]
print(x,type(x))

#[0, 0, 0, 0, 0] <class 'list'>
#[0, 0, 0, 0, 0] <class 'list'>
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
#[1, 3, 5, 7, 9] <class 'list'>
#[10, 8, 6, 4, 2] <class 'list'>
#[1, 4, 9, 16, 25, 36, 49, 64, 81] <class 'list'>
#[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99] <class 'list'>

  1. 创建4*3的二维数组
x = [[1,2,3],[4,5,6],[7,8,9],[0,0,0]]
print(x,type(x))
#[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]] <class 'list'>

x = [[0 for col in range(3)] for row in range(4)]
print(x,type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0]=1
print(x,type(x))
# [[1, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

  1. 创建一个混合列表
mix = [1,'lsgo',3.14,[1,2,3]]
print(mix)
#  [1, 'lsgo', 3.14, [1, 2, 3]]
  1. 向列表中添加元素,
    append是追加,把一个东西整体添加在列表后,extend是扩展,把一个东西里的所有元素添加在列表后。
x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
x.append('Thursday')
print(x,type(x))
print(len(x))
#['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday'] <class 'list'>
#6

x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
x.append(['Thursday','Sunday'])
print(x,type(x))
print(len(x))
#['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', ['Thursday', 'Sunday']] #<class 'list'>
#6

x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
x.extend(['Thursday','Sunday'])
print(x,type(x))
print(len(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday', 'Sunday'] #<class 'list'>
#7

x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
x.insert(2,'Sunday')   ##在位置2中插入
print(x)
print(len(x))
# ['Monday', 'Tuesday', 'Sunday', 'Wednesday', 'Thursday', 'Friday']
#6
  1. 删除列表中的元素,remove和pop都可以删除元素,前者是指定具体要删除的元素,后者是指定一个索引
# 1. list.remove(obj) 移除列表中某个值的第一个匹配项
x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
x.remove('Monday')
print(x)
#['Tuesday', 'Wednesday', 'Thursday', 'Friday']
# list.pop([index=-1])  ##移除列表中的一个元素,默认最后一个元素,并且返回该元素的值
x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
y = x.pop()
print(y)

y = x.pop(0)
print(y)

y = x.pop(-2)
print(y)
print(x)

#Friday
#Monday
#Wednesday
#['Tuesday', 'Thursday']

del var

##如果知道要删除的元素在列表中的位置,可用del语句
x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
del x[0:2]
print(x)
#['Wednesday', 'Thursday', 'Friday']

获取列表中的元素

##切片的通用写法
## 1 start
x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
print(x[3:])
print(x[-3:])
#['Thursday', 'Friday']
#['Wednesday', 'Thursday', 'Friday']
## 2 stop
x = ['Monday','Tuesday','Wednesday','Thursday','Friday']
print(x[:3])   ##???
print(x[:-3])
#['Monday', 'Tuesday', 'Wednesday']
#['Monday', 'Tuesday']

列表中的常用操作符

“”"
1.等号操作符:==
2. 连接操作符+
3.重复操作符
4.成员关系操作符 in 、not in
“”"

练习:
1.

x = [2,5,6,7,8,9,2,9,9]
x.append(15)
x.insert(int(len(x)/2),20)
x.extend([2,5,6])
x.pop(3)
x.reverse
x.sort()
print(x)

2.顶峰索引

def peakIndexInMountainArray(A):
        n = len(A)
        for i in range(n):
            if A[i] < A[i+1]:
                i += 1
            else:
                return i
peakIndexInMountainArray([1,3,5,1])

或者直接最大值索引:

def peakIndexInMountainArray(A):
        return A.index(max(A))
print(peakIndexInMountainArray([1,2,3,5,3]))

二、元组:
元组的定义语法为(元素1,元素2,……,元素n)

t1 = (1,10.31,'Python')
t2 = 1,10.31,'python'
print(t1,type(t1))
#(1, 10.31, 'Python') <class 'tuple'>
#元组至包含一个元素时,需要在元素后面添加逗号
print(8*(8))
print(8*(8,))
#64
#(8, 8, 8, 8, 8, 8, 8, 8)

# 创建二维元组
nested = (1,10.31,'python'),('data',11)
print(nested)
#((1, 10.31, 'python'), ('data', 11))

更新和删除一个元组

week = ('Monday','Tuesday','Thursday','Friday')
week = week[:2]+('Wednesday',)+week[2:]
print(week)
#('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')

元组相关操作符

# 元组的大小和内容不可更改,因此只有count和index两种方法
t = (1,10.31,'python')
print(t.count('python'))
print(t.index(10.31))
#1
#1

解压元组

t = (1,10.31,'python')
(a,b,c) = t
print(a,b,c)
# 1 10.31 python

# 解压二维元组
t = (1,10.31,('OK','python'))
(a,b,(c,d)) = t
print(a,b,c,d)
# 1 10.31 OK python

三、字符串

# 如果字符串中需要出现单引号或双引号,可以使用转义符号\对字符串中的符号进行转义
print('let\'s go')
print("let's go")
print('c:\\now')
print("C:\\Program files\\intel\\wifi\\help")

#let's go
#let's go
#c:\now
#C:\Program files\intel\wifi\help
#\\ 反斜杠符号
#\' 单引号
#\" 双引号
#\n换行
#\t横向制表符
#\r 回车
# ljust(width[,fillchar])返回一个原字符串左对齐,
#并使用fillchar填充至长度width的新字符串
# rjust(width[,fillchar])返回一个原字符串右对齐,
#并使用fillchar填充至长度width的新字符串
str4 = '1101'
print(str4.ljust(8,'0'))
print(str4.rjust(8,'0'))
#11010000
#00001101
# lstrip([chars])  截掉字符串左边的空格或指定字符
# rstrip([chars])  删除字符串末尾的空格或指定字符
# strip([chars])   在字符串上执行lstrip()和rstrip()
str5 = ' I Love LsgoGroup '  #截掉左边的空格
print(str5.lstrip())
print(str5.lstrip().strip('I'))   ##截掉I
print(str5.rstrip()) ##截掉右边的空格
print(str5.strip().strip('p'))
#I Love LsgoGroup 
#Love LsgoGroup 
#I Love LsgoGroup
#I Love LsgoGrou
#partition(sub)找到子字符串sub,把字符串分为一个三元组(pre_sub,sub,fol_sub)
# 如果字符串中不包含sub则返回(‘原字符串’,“,”)

#rpartition(sub)类似于partition()方法,不过是从右边开始查找

str5 = 'I Love LsgoGroup '
print(str5.strip().partition('o'))
print(str5.strip().partition('m'))
print(str5.strip().rpartition('o'))
#('I L', 'o', 've LsgoGroup')
#('I Love LsgoGroup', '', '')
#('I Love LsgoGr', 'o', 'up')

#replace(old,new,[,max])把字符串中的old替换成new,如果max指定,则替换不超过max次
str5 = ' I Love LsgoGroup '
print(str5.replace('I','We'))
# We Love LsgoGroup 

字符串格式化
format格式化函数

str = "{0} Love {1}".format('I','Lsgogroup')  ##位置参数
print(str)
# I Love Lsgogroup

str = "{a} Love {b}".format(a='I',b='Lsgogroup') #关键字参数
print(str)
#I Love Lsgogroup

str = "{0} Love {b}".format('I', b='lsgogroup') ##位置参数要在关键字参数之前
print(str)
#I Love lsgogroup

str = '{0:.2f}{1}'.format(27.658,'GB')  #保留小数点后两位
print(str)
#27.66GB

相关标签: 笔记 python