= ["mary", "jones", "abc", "234", "cars", "hi"]
ls_ref = ["234", "mary", "abc"] ls1
41 PG: Sort
41.1 Sort List according to sequence in another 1.
Sort the content of ls1
according to the order they appear in ls_ref
41.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']
for x in ls_ref if x in ls1] [x
['mary', 'abc', '234']
41.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
= [x for x in ls_ref if x in set_ls1]
ls_out
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]