存在许多重复元素时,从列表中删除重复元素

时间:2019-07-18 13:08:27

标签: python list

我正在尝试从列表中删除重复的元素,但无法将其删除(“ 1”),有人可以解释我在做什么错误

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
    for i in lst:
        print(i)
        if i==1:
           lst.remove(i)

预期的输出-

[2,3,4,5,6,7,2]

实际输出-

[2,3,4,5,6,7,1,2]

2 个答案:

答案 0 :(得分:0)

使用列表理解:

例如。

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(InvalidGrantException.class)
    public ResponseEntity<CustomErrorMessageTO> handleInvalidGrant(
            InvalidGrantException invalidGrantException) {

        CustomErrorMessageTO customErrorMessageTO = new CustomErrorMessageTO("Not granted or whatsoever");

        return new ResponseEntity<>(customErrorMessageTO, HttpStatus.UNAUTHORIZED);
    }
}

class CustomErrorMessageTO {

    private String message;

    public CustomErrorMessageTO(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

O / P:

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
new_list = [x for x in lst if x != 1]
print(new_list)

OR

从列表中删除所有重复的元素,使用[2, 3, 4, 5, 6, 7, 2]

例如。

set

O / P:

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
print(list(set(lst)))

答案 1 :(得分:0)

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
for i in lst[:]:
    print(i)
    if i==1:
        lst.remove(i)
print(lst)
# [2, 3, 4, 5, 6, 7, 2] 

您要遍历一个更改列表,这是错误的