学习简述:三元运算,列表,元组,字符串,字典
三元运算其实就是为了缩减代码而产生,可以把三句话用一句来表示。
a,b,c = 1,2,4
d = a if b>c else c
意思就是如果b>c是正确的,那么d = a,否则d = c,相当于:a,b,c = 1,2,4
if b>c:
d = a
else:
d = c
下面我们好好说一说列表:首先列表用" [] "符号表示,我们来说说列表涉及的切片,增,删,插入,改等各种方法
#切片
names = ['aa','bb','cc','dd']
print (names[1:3])
print (names[-3:-1])#默认是从左往右
#增
names = ['aa','bb','cc','dd']
names.append("ee")
print (names)
#插入
names = ['aa','bb','cc','dd']
names.insert(1,"ee") #1:你想插入的位置,'ee':你想要加入的内容
print (names)
#删
names = ['aa','bb','cc','dd']
names.remove('cc')#
del names[0] #
names.pop(0) #这三者等价
print (names)
#改
names = ['aa','bb','cc','dd']
names[0] = 'niuniu'
print (names)
#索引
names = ['aa','bb','cc','dd','aa']
print (names.index('bb')) #索引找的这个东西必须是在列表里的
#合并
names = ['aa','bb','cc','dd','aa']
names2 = [1,2,3,4]
names.extend(names2)
print(names)
说说还有些价值的浅copynames = ['aa','bb','cc','dd','aa']
p1 = names.copy()
p2 = names.copy()
names[0] = '11'
print (names)
print (p1)
print (p2)
输出结果你会发现,只有names的'aa'变为了'11',而p1,p2中的未改变,因为copy是浅copy,若再往深改进,你就会看到变化names = ['aa','bb',['age',12],'dd','aa']
p1 = names.copy()
p2 = names.copy()
names[2][0] = 'salary'
print (names)
print (p1)
print (p2)
#结果
['aa', 'bb', ['salary', 12], 'dd', 'aa']
['aa', 'bb', ['salary', 12], 'dd', 'aa']
['aa', 'bb', ['salary', 12], 'dd', 'aa']
这并不代表没用,比如如果夫妻两人相创建一个联合账号,丈夫加入取走500,那么妻子等于也少了500person = ['names',['salary',10000]]
p1 = person[:]
p2 = person[:]
p1[0] = 'husband'
p2[0] = 'wife'
p1[1][1] = '500'
print (p1)
print (p2)
#结果
['husband', ['salary', '500']]
['wife', ['salary', '500']]
元组其实就相当于一个小的列表,但是注意,元组是只读的,只能切片和索引。字符串
特性:不可修改
可以切片
name = 'niu' name.capitalize() #首字母大写 name.casefold() #大写全部变小写 name.center(50,"-") #输出 '---------------------niu----------------------' name.count('niu') #统计niu出现次数 name.encode() #将字符串编码成bytes格式 name.endswith("niu") #判断字符串是否以niu结尾 "niu\tZ".expandtabs(10) #输出'niu Z', 将\t转换成多长的空格 name.find('A') #查找A,找到返回其索引, 找不到返回-1
字典
特性:字典是无序的,但key是唯一的,所以天生去重
#改
score = {
'studen1':90,
'student2':78,
'student3':88,
'student4':56
}
score['student2'] = 100
print (score)
# >>>{'studen1': 90, 'student2': 100, 'student3': 88, 'student4': 56}
#增
score['student5'] = 23
print (score)
# >>>{'studen1': 90, 'student2': 100, 'student3': 88, 'student4': 56, 'student5': 23}
#删
del score['student2']
score.pop('student2')
score.popitem() #随机删
print (score)
#查
print(score['student4'])
print(score.get('student4'))
#其他
print(score.values())
print(score.keys())
#循环
for i in score:
print (i,score[i])