- 学习测试开发的Day62
- 学习时间1小时10分钟
- 第六次全天课20190119(下午视频2H30M-3H15M)
小题:写一个函数,有2个参数,一个是列表,一个是待删除的元素,函数实现在列表中删除所有的待删除元素,然后把删除后的列表剩余元素返回。
自己的:
'''写一个函数,有2个参数,一个是列表,一个是待删除的元素,函数实现在列表中删除所有的待删除元素,然后把删除后的列表剩余元素返回。'''
def list_del(l,e):
if not isinstance(l,list):
return None
for i in l:
if i==e:
l.remove(e)
return l
l=[1,2,3,4,5,4]
l2=1,2
e=4
print(list_del(l,e))
print(list_del(l2,e))
PS D:\0grory\day6> python .\list_del.py
[1, 2, 3, 5]
None
teacher
while 条件:
删除之
def remove_sth_in_list(L,element):
if not isinstance(L,list):
return None
while element in L:
L.remove(element)
return L
print(remove_sth_in_list([1,2,1,2,1,2],1))
PS D:\0grory\day6> python .\remove_sth_in_list.py
[2, 2, 2]
删除列表
image.png
列表运算符
image.png
>>> len([1,2,3])
3
>>> [1,2,3]*10
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 1 in [1,2]
True
>>> for i in [1,2,3]:
... print(i)
...
1
2
3
>>>
列表截取
Python的列表截取与字符串操作类似,均使用切片完成。
L = ['spam', 'Spam', 'SPAM!‘]
Python表达式 | 结果 | 描述 |
---|---|---|
L[2] | 'SPAM!' | 读取列表中第三个元素 |
L[-2] | 'Spam' | 读取列表中倒数第二个元素 |
L[1:] | ['Spam', 'SPAM!'] | 从第二个元素开始截取列表 |
列表函数&方法
image.png
max里面的格式必须相同,不然会报错
>>> max([1,2,3])
3
>>> max([1,3,4,"a"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
对于不支持索引和切片的数据加索引,回报object is not subscriptable
>>> 1[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
>>>
python六剑客map list
>>> min([12,3,4])
3
>>> "I am a boy".split()
['I', 'am', 'a', 'boy']
>>> map(len,"I am a boy".split())
<map object at 0x00000171A4FE6FD0>
>>> list(map(len,"I am a boy".split()))
[1, 2, 1, 3]
>>> max(list(map(len,"I am a boy".split())))
3
>>>
map的用法,其中for的用法和list用法一样,用来遍历的
>>> map(len,["ab","dec"])
<map object at 0x00000171A4FE6EB8>
>>> list(map(len,["ab","dec"]))
[2, 3]
>>> for i in map(len,["ab","dec"]):
... print(i)
...
2
3
>>>
list的用法
>>> list("abc")
['a', 'b', 'c']
>>> "".join(["a","b","c"])
'abc'
>>> "*".join(["a","b","c"])
'a*b*c'
>>>
小练习:单词中去掉所有的a
abandon
自己的:
s="abandon"
def remove_a(s):
s2=""
l=list(s)
for i in l:
if i!='a':
s2+=i
return s2
print(remove_a(s))
PS D:\0grory\day6> python .\remove_a.py
bndon
PS D:\0grory\day6>
老师的
算法:
1.把单词转换为字母的列表---->list
2.遍历,找到a,替换成""
3.把列表用""join起来
法1-for:
s="abandon"
s=list(s)
for i in range(len(s)):
if s[i]=="a":
s[i]=""
print("".join(s))
PS D:\0grory\day6> python .\remove_a_teacher.py
bndon
法2-while:
s="abandon"
s=list(s)
while "a" in s:
s.remove("a")
print("".join(s))