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

前端 未结 8 886
醉话见心
醉话见心 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条回答
  •  猫巷女王i
    2021-02-02 06:05

    What you are trying to do can almost certainly be achieved with a set.

    >>> x = set([1,2,3])
    >>> x.add(2)
    >>> x
    set([1, 2, 3])
    >>> x.add(4)
    >>> x.add(4)
    >>> x
    set([1, 2, 3, 4])
    >>> 
    

    using a set's add method you can build your unique set of ids very quickly. Or if you already have a list

    unique_ids = set(id_list)
    

    as for getting your inputs in numeric form you can do something like

    >>> ids = [int(n) for n in '350882 348521 350166\r\n'.split()]
    >>> ids
    [350882, 348521, 350166]
    

提交回复
热议问题