Getting elements from a list that has a prefix

Question:

Let’s say I have a few lists:

list = ["MacOS-1", "MacOS-2", "Windows-1", "Windows-2"]
maclist = []
windowslist = []

How do I get elements from "list" and sort them into "maclist" or "windowslist" according to if they have "MacOS" or "Windows" in front of them?

I was thinking: (I haven’t tested this yet)

for element in list:
  if "MacOs" in element:
    maclist.append(element)
  elif "Windows" in element:
    windowslist.append(element)

Thanks in advance…

Asked By: pico

||

Answers:

You can use startswith function in Python.

for element in list:
  if element.startswith("MacOS"):
    maclist.append(element)
  elif element.startswith("Windows"):
    windowslist.append(element)

In your code, you don’t only check prefixes, also you check all substrings in any index range.

Or, you can use the below implementation:

macos_list = [item for item in item_list if item.startswith("MacOS")]
windows_list = [item for item in item_list if item.startswith("Windows")]
Answered By: gokhan_ozeloglu

You may want to look into Radix Trees, it is the most efficient way.
Also lots of solutions online. Eg if the list is long, and you have to do this over and over, then you can sort the list once and then do a biary search on it in log(N), then look in the neighbourhood of the results.

Answered By: user96265
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.