25  PG: Sort

25.1 Sort List according to sequence in another 1.

Sort the content of ls1 according to the order they appear in ls_ref

ls_ref = ["mary", "jones", "abc", "234", "cars", "hi"]
ls1 = ["234", "mary", "abc"]

25.1.1 My Solution

ls_out = []

for x in ls_ref:
    if x in ls1:
        ls_out.append(x)
    else:
        continue
    
print(ls_out)
['mary', 'abc', '234']
[x for x in ls_ref if x in ls1]
['mary', 'abc', '234']

25.1.2 Optimized

To make the algorithm more efficient, you can:

  • Convert ls1 into a set to reduce the time complexity of the membership test from O(n) to O(1) (constant time).
  • Use a list comprehension for a cleaner and more Pythonic solution.
# Convert ls1 to a set for O(1) lookup
set_ls1 = set(ls1)
print(set_ls1)

# List comprehension with O(1) lookups
ls_out = [x for x in ls_ref if x in set_ls1]

print(ls_out)
{'234', 'abc', 'mary'}
['mary', 'abc', '234']
dict(zip(list(range(0, len(ls_ref))), ls_ref))
{0: 'mary', 1: 'jones', 2: 'abc', 3: '234', 4: 'cars', 5: 'hi'}
sorted("This is a test string from Andrew".split(), key=str.casefold)
sorted({0: 'mary', 1: 'jones', 2: 'abc', 3: '234'})
[0, 1, 2, 3]