Tips for arranging a secondary list according to the order of the first list?

Struggling to sort an ordered list based on the order of an unordered list? I attempted to do so by manipulating the indexes of each element in both lists without success. If anyone has faced a similar challenge or knows the right function to use, I'd appreciate the guidance.

unordered_list = ['North_America', 'Europe', 'Asia', 'Antarctica',  'Australia', 'Africa']

ordered_list =   ['Africa.jpg', 'Asia.jpg', 'Antarctica.jpg', 'Australia.jpg', 'Europe.jpg', 'North_America.jpg']

# The desired reordering for this case: [5,4,1,2,3,1]

The desired output:

ordered_list = ['North_America.jpg', 'Europe.jpg', 'Asia.jpg', 'Antarctica.jpg',  'Australia.jpg', 'Africa.jpg']

Answer №1

Below is the resulting output:

['North_America.jpg', 'Europe.jpg', 'Asia.jpg', 'Antarctica.jpg',  'Australia.jpg', 'Africa.jpg']

This snippet represents the code used to generate the list above:

unordered_list = ['North_America', 'Europe', 'Asia', 'Antarctica',  'Australia', 'Africa']
ordered_list =   ['Africa.jpg', 'Asia.jpg', 'Antarctica.jpg', 'Australia.jpg', 'Europe.jpg', 'North_America.jpg']

corrected_list = []

for x in unordered_list:
    for y in range(len(ordered_list)):
        if x in ordered_list[y]:
            corrected_list.append(ordered_list[y])
            break
            
print(corrected_list)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to make a nested array column in pyspark?

I have been attempting to achieve a specific result in pyspark 2.4, but I am unsure of the best approach. My goal is to take a nested array and use it as the default value for a new column in my dataframe. from pyspark.sql import SparkSession from pyspar ...

Integrate the form outcome into the search results organized by book titles

There is a search form for finding books on the page, but I am having trouble adding the result of a particular book to the $scope.books object. Can you help me with this? Here's the code snippet: https://jsfiddle.net/dbxtcw9w/2 Thank you for your ...

Having trouble importing Web3 in Python within the colab.research.google.com environment

Trying to incorporate the Web3 library into a Google Colab environment at colab.research.google.com/, using the code snippet: from web3 import Web3 after installing it with the following command: !pip install web3. However, encountering th ...

Error encountered in Django due to repeated AJAX calls causing a closed socket issue: [WinError 10053] The established connection was abruptly terminated by the software running on your host machine

Trying to integrate live search functionality using the Select2 jQuery plugin in my Django 1.11.4 project has led to some server-related issues. Upon entering text into the search box, the server seems unable to handle the volume of requests and ends up sh ...

Creating a dynamic MPTT structure with expand/collapse functionality in a Django template

I am looking for a way to display my MPTT model as a tree with dropdown capability (open/close nodes with children) and buttons that can expand/collapse all nodes in the tree with just one click. I have searched for examples, but the best I could find is ...

What is the presence of the term "sort" in this JSON document from elasticsearch?

While working on indexing data into Elasticsearch, I encountered a puzzling issue related to the appearance of the ""sort"" attribute. Interestingly, this attribute was not included in my mapping nor in the data being indexed. This instance prom ...

Is there a way to extract the text from a textarea using webdriver?

When attempting to retrieve the contents of a textarea within an HTML form using webdriver in Python, I am able to get the text, but the newlines are missing. Despite consulting the selenium docs, which provide limited information: class selenium.webdrive ...

Using Python's Selenium for Page Object Model (POM) implementation

As a newcomer to automation testing, I am currently learning how to automate tests using Selenium with Python and the page object model. While watching tutorials on YouTube, I noticed that logging in is being done for every test case, which seems redundant ...

Performing a numpy calculation in Python to sum every 3 rows, effectively converting monthly data into quarterly data

I have a series of one-dimensional numpy arrays containing monthly data. My goal is to aggregate these arrays by quarter and create a new array where each element represents the sum of three consecutive elements from the original array. Currently, I am ut ...

Using a separate iteration of Python while conducting an NPM installation

I have admin privileges on a VPS running CentOS 5.9 with Python 2.4.3 installed by default. I decided to upgrade to Python 2.7.3 using the commands below (I opted for make altinstall instead of make install): wget http://www.python.org/ftp/python/2.7.3/Py ...

Achieving permanent proxy settings in Firefox Webdriver: A step-by-step guide

As Geckodriver does not allow direct proxy settings, I will manually adjust it with the following code snippet: from selenium import webdriver myProxy = "xxxxxxxxx:yyyy" ip, port = myProxy.split(":") profile = webdriver.FirefoxProfile() profile.set_pref ...

Tips for transforming gridded temperature data in CSV format (organized by latitude and longitude) into a raster map

Recently, I acquired a dataset that shows the average temperature change across the entire US, but it is formatted with lat/long range. The original csv file can be found here: original csv I am attempting to convert this data into a raster for visualizat ...

Utilize pymssql to export data to a CSV file with the column names automatically set as headers

Below is a script that I have created for the purpose of i) connecting to a database, ii) executing a query, iii) saving the results as a CSV file, and iv) sending the output via email. Although everything is functioning correctly, there seems to be an is ...

A guide on repositioning draggable child elements within the same parent using Selenium with Python

Consider the following HTML structure: <div name="parent"> <div name="child one"> </div> <div name="child two"> </div> <div name="child three"> </div> <div name="child four"> </div> < ...

Obtaining and storing the 'text' attribute from a JSON tweet element into a string array using Python

My MongoDB collection is filled with tweets that I've gathered and now I want to analyze their sentiment. However, I only want to analyze the 'text' field of each tweet. I previously had a code snippet to check if the element had a text fiel ...

Creating a visual grid using a combination of x's and blank spaces arranged in rows according to user input

As part of my computer programming homework (for Year 8 in the UK), I need to create a program based on the following criteria: Develop a function that takes two numbers as parameters. The first number determines the amount of spaces to be displayed, while ...

Encountering difficulties while attempting to decode specific characters from API calls in Django

The response I am receiving from an API contains a character \x96 Upon making the API call, the following error is triggered: 'ascii' codec can't encode character u'\x96' in position 56: ordinal not in range(128) This ...

When attempting to automate tasks with selenium, I encountered a problem where the mouseover function was not functioning

Currently, I am working on automating a website and facing an issue while trying to access a specific submenu item by hovering over a menu. After extensive research, I found that using mouseover would be the best approach since the submenu only appears w ...

Is it possible to automate Chrome browser using Selenium without using chromedriver?

I've been attempting to automate a website but have encountered issues with detecting chromedriver. Despite trying various methods such as changing the cdc_ part of the chromedriver and using a different user agent, it still identifies the presence of ...

Steps for separating data within a CSV cell and generating additional rows

I just recently started learning how to code in Python. After searching through various resources, I couldn't find a direct solution to my current issue. Here's the problem I'm facing: I have a csv file structured like this: Header1, Heade ...