美文网首页
列表中删除数据遇到的两个问题

列表中删除数据遇到的两个问题

作者: Z_JoonGi | 来源:发表于2019-03-17 11:21 被阅读0次

    删除列表中所有小于60的数字

    问题1: 通过元素删除的时候可能出现删不干净的问题

    scores = [10, 50, 90, 89, 45, 70]
    for score in scores:
        if score < 60:
            scores.remove(score)
    
    print(scores, score)    # [50, 90, 89, 20, 70]
    
    """
    scores = [10, 50, 90, 89, 45, 70]
    score = 10   if 10 < 60    scores.remove(10)       scores = [50, 90, 89, 45, 70]  
    score = 90   if 90 < 60
    score = 89   if 89 < 60
    score = 45   if 45 < 60    scores.remove(45)       scores = [50, 90, 89, 70] 
    """
    
    解决问题1:
    scores = [10, 50, 90, 89, 45, 70]
    scores2 = scores[:]
    for score in scores2:
        if score < 60:
            scores.remove(score)
    del scores2    # score2只是提供遍历用的,用完后没有其他用处,可以直接删除
    print(scores, score)
    
    上面的简写
    scores = [10, 50, 90, 89, 45, 70]
    for score in scores[:]:
        if score < 60:
            scores.remove(score)
    print(scores, score)
    
    """
    scores = [10, 50, 90, 89, 45, 70]
    scores2 = [10, 50, 90, 89, 45, 70]
    score = 10   if 10<60  scores.remove(10)   scores = [50, 90, 89, 45, 70]
    score = 50   if 50<60  scores.remove(50)   scores = [90, 89, 45, 70]
    score = 90   if 90<60
    score = 89   if 89<60
    score = 45   if 45<60  scores.remove(45)   scores = [90, 89,70]
    score = 70   if 70<60
    """
    

    问题2:通过下标删除满足要求的元素的时候,出现下标越界的错误

    print('====================问题2=====================')
    scores = [10, 50, 90, 89, 45, 70]
    for index in range(len(scores)):
        if scores[index] < 60:
            del scores[index]
    
    print(scores)
    """
    scores = [10, 50, 90, 89, 45, 70]
    for index in range(6)  
    index = range(6)  index = (0,1,2,3,4,5)
    index = 0   if scores[0]<60   if 10<60   del scores[0]  scores = [50, 90, 89, 45, 70]
    index = 1   if scores[1]<60   if 90<60   
    index = 2   if scores[2]<60   if 89<60
    index = 3   if scores[3]<60   if 45<60   del scores[3]  scores = [50, 90, 89, 70]
    index = 4   if scores[4]<60  (out of range)
    """
    
    解决问题2:
    scores = [10, 50, 90, 89, 45, 70]
    index = 0
    while index < len(scores):
        if scores[index] < 60:
            del scores[index]
            continue
        index += 1
    
    print(scores)
    """
    scores = [10, 50, 90, 89, 45, 70]   
    index = 0
    while 0 < 6    if 10<60   del scores[0]   scores = [50, 90, 89, 45, 70] 
    while 0 < 5    if 50<60   del scores[0]   scores = [90, 89, 45, 70]
    while 0 < 4    if 90<60   index += 1  index = 1
    while 1 < 4    if 89<60   index += 1  index = 2
    while 2 < 4    if 45<60   del scores[2]   scores = [90, 89,70]
    while 2 < 3    if 70<60   index += 1  index = 3  
    while 3 < 3 
    print(scores)  -  [90, 89,70] 
    """
    

    相关文章

      网友评论

          本文标题:列表中删除数据遇到的两个问题

          本文链接:https://www.haomeiwen.com/subject/llnymqtx.html