最近重学python基础,感觉基础知识还是得扎实才能走得更远,整理了一些笔记和大家分享。参考书目:《Head First Python》
列表
remove只能在知道要删的值时使用, pop取可选索引值作为参数
test
= [1,2,3,4]
test
.remove
(3)
test
'''
[1,2,4]
'''
test
.pop
(1)
test
'''
#pop 不指定参数则默认弹出最后一个。
pop的元素可被解释器回收,也就是可被赋值 如 x = test.pop(),但remove不可以做到
[1,4]
'''
extend是将列表中所有元素依次加在最后,append是将整个列表加在最后,insert(index,value)
x1
= [1,2,3]
x1
.append
([4,5])
x1
'''
[1, 2, 3, [4, 5]]
#如果append([]),会把一个空列表作为元素加在最后,变成[1,2,3,[]]
'''
x2
= [1,2,3]
x2
.extend
([4,5])
x2
'''
[1, 2, 3, 4, 5]
#如果extend([]),和原来没啥变化
'''
x2
.insert
(2,6)
x2
'''
[1,2,6,3,4,5]
'''
列表的复制
赋值操作符不能把一个列表复制到另一个列表。拷贝值用list.copy()
a
= [1,2,3]
b
= a
b
.append
(4)
a
''' [1,2,3,4]'''
a
.append
(5)
b
''' [1,2,3,4,5]'''
c
= b
.copy
()
b
.append
(6)
c
'''[1,2,3,4,5]'''
字典
字典无序。键值对是关键。字典查找速度快
for k
,v
in dic
.items
():
print (f
"{k} is {v}.")
**字典的键必须初始化。**setdefault方法,防止KeyError(如果试图访问一个不存在的键的关联值会报错)
vowels
= ['a','e','i','o','u']
word
= input("Input a word: ")
found
= {}
for letter
in word
:
if letter
in vowels
:
found
.setdefault
(letter
,0)
found
[letter
] +=1
for k
,v
in found
.items
():
print(f
"{k} has appeared {v} times")
'''
Input a word: haaaley
a has appeared 3 times
e has appeared 1 times
'''
集合
集合用大括号表示, 也可以使用set(str),把字符串里每个字母变成一个集合元素集合拼接用union, set1.union(set(str2)), 结果也是一个集合比较两个集合中差异,set_a.difference(set_b)集合取交集, set_a.intersection(set_b)空集合为set(), 尽管集合用{}表示, 但{}被认为是空字典
vowel
= set('aeiou')
word
= input("Input a word: ")
result
= set(word
).intersection
(vowel
)
for letter
in result
:
print(letter
)
元组
元组不可变(优点是性能高,列表可变但可变总会带来内存的影响)元组在构建时必须含有一个逗号。(‘a’) 是字符串,(‘a’,)为元组
函数
函数注解
def search4vowels(word
:str)->set:
'''this is a docstring'''
vowels
= set('aeiou')
return vowels
.intersection
(set(word
))
help(search4vowels
)