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

前端 未结 8 857
醉话见心
醉话见心 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:12

    There are a couple things going on with your example. You have a list containing a string of numbers and newline characters:

    list = ['350882 348521 350166\r\n']
    

    And you are trying to find a number ID within this list:

    id = 348521
    if id not in list:
        ...
    

    Your first conditional is always going to pass, because it will be looking for integer 348521 in list which has one element at index list[0] with the string value of '350882 348521 350166\r\n', so integer 348521 will be added to that list, making it a list of two elements: a string and an integer, as your output shows.

    To reiterate: list is searched for id, not the string in list's first element.

    If you were trying to find if the string representation of '348521' was contained within the larger string contained within your list, you could do the following, noting that you would need to do this for each element in list:

    if str(id) not in list[0]: # list[0]: '350882 348521 350166\r\n'
        ...                    #                  ^^^^^^
    

    However be aware that you would need to wrap str(id) with whitespace for the search, otherwise it would also match:

    2348521999
     ^^^^^^
    

    It is unclear whether you want your "list" to be a "string of integers separated by whitespace" or if you really want a list of integers.

    If all you are trying to accomplish is to have a list of IDs, and to add IDs to that list only if they are not already contained, (and if the order of the elements in the list is not important,) then a set would be the best data structure to use.

    ids = set(
        [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
    )
    
    # Adding an ID already in the set has no effect
    ids.add(348521)
    

    If the ordering of the IDs in the string is important then I would keep your IDs in a standard list and use your conditional check:

    ids = [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
    
    if 348521 not in ids:
        ...
    

提交回复
热议问题