• notice
  • Congratulations on the launch of the Sought Tech site

Python rearranges a list based on another list

I want to rearrange a list based on another list that have common element.

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

The above list has common "a", "b" and "c" as common elements.The expected result is as follows

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

Thanks Sky in advance

uj5u.com enthusiastic netizens replied:

my_list=['q','s','b','f' span>,'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']

uj5u.com enthusiastic netizens replied:

Create a custom key, sortedas in thisin file shown .Set arbitrarily high values ​​for letters that do not appear in base_list so that they end up in the back.Since sortedis considered to be stable, Those not presentbase_list will keep the 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']

uj5u.com enthusiastic netizens replied:

One ​​(probably not the best) 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']

uj5u.com enthusiastic netizens replied:

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()

Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

order atorvastatin 80mg without preion & lt;a href="https://lipiws.top/"& gt;order atorvastatin 20mg pill& lt;/a& gt; buy atorvastatin 20mg online

Axqmhm

2024-03-08

Leave a Reply

+