Home > Blockchain >  Python rearrange list based on another list
Python rearrange list based on another list

Time:12-29

I want to rearrange a list based on another list which have common elements between them.

my list = ['q','s','b','f','l','c','x','a']
base_list = ['z','a','b','c']

Above lists have common 'a','b' and 'c' as common elements.the expected outcome for is as below

my_result = ['a','b','c','q','s','f','l','x']

Thanks in Advance Sky

CodePudding user response:

Create a custom key for sorted as shown in this document. Set the value arbitrarily high for the letters that don't appear in the base_list so they end up in the back. Since sorted is considered stable those that aren't in the base_list will remain untouched in terms of original order.

l = ['q','s','b','f','l','c','x','a']
base_list = ['z','a','b','c']

def custom_key(letter):
    try:
        return base_list.index(letter)
    except ValueError:
        return 1_000

sorted(l, key=custom_key)
['a', 'b', 'c', 'q', 's', 'f', 'l', 'x']

CodePudding user response:

my_list = ['q','s','b','f','l','c','x','a']
base_list = ['z','a','b','c']

res1=[x for x in base_list if x in my_list] # common elements
res2=[x for x in my_list if x not in res1] # 
res3=res1 res2

Output :

['a', 'b', 'c', 'q', 's', 'f', 'l', 'x']

CodePudding user response:

A (probably non optimal) way:

>>> sorted(my_list, key=lambda x: base_list.index(x) if x in base_list 
                                                     else len(base_list) 1)

['a', 'b', 'c', 'q', 's', 'f', 'l', 'x']

CodePudding user response:

combined_list = []
for element in my_list:
    If  combined_list.contains(element) == false
        Combined_list.append(element)
for element in old_list:
    If combined_list.contains(element) == false
        Combined_list.append(element)
Combined_list.sort()
  • Related