一.关系运算符
== , !=, > , < , >= , <= , 其表达式结果都为布尔值
二.逻辑运算符
and(2个皆True 才是 True) , or(1个是True 就返回True ), not , 表达式结果都是布尔值
三.基本数据结构
1. 列表(List)
(1)定义
number = ['a','b','c']
(2)增删改查
number = ['a','b','c']
number.insert(1,'d') #括号内第一个填的是增加内容的索引,反映list有序
print(number)
b = ['5','6','7']
a = ['1','2','3']
a.extend(b)
print(a) output:['1', '2', '3', '5', '6', '7']
a.remove ('3') output:['1', '2', '5', '6', '7']#要确保删除的元素在list中,否则error
a.pop() output:['1', '2', '5', '6'] #可添加索引弹出指定元素,一般就弹出最后一个元素
new = a[0:2] #可以用切片来取出一些元素作操作
del a[1:3] #用切片删除,一般不用,无返回值
a.clear() #清空列表
a[0:2] = ['100','200'] #范围更改
a[0] = '100' #修改元素
index_of_2 = a.index(2) #返回元素索引
count_of_2 = a.count(2) #返回元素出现的次数
#字符串反转:
可以用str[::-1],也可以先转成list再反转,即:
a = 'inevitable'
a1 = list(a)
a1.reverse()
print(a1)
a2 = ''.join(a1)
print(a2)
output:['e', 'l', 'b', 'a', 't', 'i', 'v', 'e', 'n', 'i']
elbative
fruits = []
def stashPush (param):
fruits.append(param)
def stashPop():
return fruits.pop() #默认删除最后一个元素,并且存在返回值,返回删除的元素
#实现了“后进先出”的栈结构
2.元组
(1)有序的不可变集合,也被被称为只读列表,即数据可以被查询,但不能被修改。
(2)里面的列表可以改变
tuple = (1, 2, 3, [1, 4, 7])
print(tuple)
tuple[3][2] = 100
print(tuple)
# Output:
(1, 2, 3, [1, 4, 7])
(1, 2, 3, [1, 4, 100])
3.字典
(1)是无序存储的,且key必须是可哈希的。可哈希表示 key 必须是不可变类型,如:数字、字符串、元组。
(2)
dic = {'name':'nls','age':18,'job':'teacher'}
print(dic)
print(dic['name'])
print(dic['age'])
print(dic['job'])
#Output:{'name': 'nls', 'age': 18, 'job': 'teacher'}
nls
18
teacher
dic['gender'] = 'male'
dic['gender'] = 'female' #增加键值的方式:没有就直接添加,有就修改
output : {'name': 'nls', 'age': 18, 'job': 'teacher', 'gender': 'female'}
dic.pop('name') #删除操作
name1 = dic.pop('name') #pop有返回值,赋给name1
print (name1) #取出value
if 'name' in dic:
print('姓名在字典中') #查找
for i in dic.items(): #作为元组列出
print (i)
print (i[0])
print (i[1]) #output:('name', 'nls')
name
nls
('age', 18)
age
18
('job', 'teacher')
job
teacher
for i in dic: #取所有键
print (i) #output:name
age
job
for i in dic.keys(): #output:name
print (i) age
job
for i in dic.values(): #取所有的value
print (i) output:nls
18
teacher
4.集合
(1)是无序的
(2)
set = {1,2,3,'a','b','c'}
set.add('d') #增加元素
list1 = [1,2,3,3,3,3]
set1 = set(list1) #对列表去重操作
list2 = list(set1) #输出1,2,3
listAll = [1, 2, 3, 3, 4, 5] # 有重复元素的列表
t = {} # 创建一个空字典
listAll = [1,2,3,3,3,3] #利用字典key的唯一性去重
for i in listAll:
t[i] = ''
listResult = []
for key in t.keys():
listResult.append(key)
set.remove('a') #删除元素
'a' in set #查找元素
set1 = {1,2,3,4,5} #取交集
set2 = {3,4,5,6,7}
print(set1 & set2) output:{3, 4, 5}
print(set1 | set2) #取并集
print(set1 - set2) #取差集
四.基本数据结构的转换
tuple1 = tuple(original_list)
set1 = set(original_list) 以此类推
五.流程控制
num = 10 #判断是否是素数
i = 2
while i < num:
if num % i == 0:
print(f"{num} 不是素数,因为它可以被 {i} 整除。")
break
i += 1
else:
print(f"{num} 是一个素数!")
letters = ['A','B','C']
i = 0
for letter in letters:
i = i+1
if (i == 2):
print('B') #输出特定元素
fruits = ["apple", "banana", "cherry"]
for index,item in enumerate(fruits):
if index == 2:
print(item) output: cherry