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

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

    I agree with other answers that you are doing something weird here. You have a list containing a string with multiple entries that are themselves integers that you are comparing to an integer id.

    This is almost surely not what you should be doing. You probably should be taking input and converting it to integers before storing in your list. You could do that with:

    input = '350882 348521 350166\r\n'
    list.append([int(x) for x in input.split()])
    

    Then your test will pass. If you really are sure you don't want to do what you're currently doing, the following should do what you want, which is to not add the new id that already exists:

    list = ['350882 348521 350166\r\n']
    id = 348521
    if id not in [int(y) for x in list for y in x.split()]:
        list.append(id)
    print list
    

提交回复
热议问题