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

前端 未结 8 856
醉话见心
醉话见心 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.

提交回复
热议问题