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

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

    Your list just contains a string. Convert it to integer IDs:

    L = ['350882 348521 350166\r\n']
    
    ids = [int(i) for i in L[0].strip().split()]
    print(ids)
    id = 348521
    if id not in ids:
        ids.append(id)
    print(ids)
    id = 348522
    if id not in ids:
        ids.append(id)
    print(ids)
    # Turn it back into your odd format
    L = [' '.join(str(id) for id in ids) + '\r\n']
    print(L)
    

    Output:

    [350882, 348521, 350166]
    [350882, 348521, 350166]
    [350882, 348521, 350166, 348522]
    ['350882 348521 350166 348522\r\n']
    

提交回复
热议问题