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

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

    If you really don't want to change your structure, or at least create a copy of it containing the same data (e.g. make a class property with a setter and getter that read from/write to that string behind the scenes), then you can use a regular expression to check if an item is in that "list" at any given time, and if not, append it to the "list" as a separate element.

    if not re.match("\b{}\b".format(348521), some_list[0]): some_list.append(348521)

    This is probably faster than converting it to a set every time you want to check if an item is in it. But using set as others have suggested here is a million times better.

    0 讨论(0)
  • 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']
    
    0 讨论(0)
提交回复
热议问题