Appending an id to a list if not already present in a string

前端 未结 8 855
醉话见心
醉话见心 2021-02-02 05:45

I am trying to check if id is in a list and append the id only if its not in the list using the below code..however I see that the id is getting appended even though id is alre

8条回答
  •  别跟我提以往
    2021-02-02 06:08

    7 years later, allow me to give a one-liner solution by building on a previous answer. You could do the followwing:

    numbers = [1, 2, 3]
    

    to Add [3, 4, 5] into numbers without repeating 3, do the following:

    numbers = list(set(numbers + [3, 4, 5]))
    

    This results in 4 and 5 being added to numbers as in [1, 2, 3, 4, 5]

    Explanation:

    Now let me explain what happens, starting from the inside of the set() instruction, we took numbers and added 3, 4, and 5 to it which makes numbers look like [1, 2, 3, 3, 4, 5]. Then, we took that ([1, 2, 3, 3, 4, 5]) and transformed it into a set which gets rid of duplicates, resulting in the following {1, 2, 3, 4, 5}. Now since we wanted a list and not a set, we used the function list() to make that set ({1, 2, 3, 4, 5}) into a list, resulting in [1, 2, 3, 4, 5] which we assigned to the variable numbers

    This, I believe, will work for all types of data in a list, and objects as well if done correctly.

提交回复
热议问题