[python面试题] 删除列表中所有的3和4

# 删除所有的3和4
a = [3, 4, 5, 3, 3, 4, 5, 3, 4, 3, 5]

# 0. 边遍历边删除列表里的元素的弊端,删掉一个,后面的元素会顶上,导致删不全

a1 = a.copy()

for i in a1:
    # print(i)
    if i == 3 or i == 4:
        a1.remove(i)

print(a1)

# 1. 遍历一个列表,去删拷贝的列表

b = a.copy()
for i in a:
    if i == 3 or i == 4:
        b.remove(i)

print(b)

# 2. 使用while True,获取最后的索引,从列表最右边开始删,避免顶位带来的弊端
c = a.copy()
i = len(c) - 1

while i >= 0:
    j = c[i]
    if j == 3 or j == 4:
        c.remove(j)
    i -= 1

print(c)

# 3. 使用另外一个列表l记录要删除的元素,然后再遍历l,使用remove去删除元素
l = []
d = a.copy()
for i in d:
    if i == 3 or i == 4:
        l.append(i)

for i in l:
    d.remove(i)

print(d)

# 4. 从后往前遍历去删除
e = a.copy()
for i in range(len(e) - 1, -1, -1):  # 从 len(e)-1 到 0删除3和4
    j = e[i]
    if j == 3 or j == 4:
        e.remove(e[i])

print(e)

总结:

    边遍历边删除列表里的元素的弊端,删掉一个,后面的元素会顶上去,占了之前空的坑,导致删不全,所以为了删掉所有3和4,比较有效的方法就是从后往前遍历去删除。

发布了26 篇原创文章 · 获赞 23 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/simuLeo/article/details/80136287
今日推荐