简体   繁体   中英

Sort an input by order of importance

I am not a coder but understand python basics. I want my user to input a random list such as:

Reuters
The New York Times
The Wall Street Journal
Associated Press
Financial Times

and for my code to sort it based on the index postion:

outlet = [ 'The Wall Street Journal', 'The New York Times', 'Associated Press', 'Reuters', 'Financial Times', 'USA Today','Bloomberg','CNBC']

so it prints ordered and on a new line:

The Wall Street Journal 
The New York Times
Associated Press
Reuters
Financial Times

Thank you!

The code I have so far is as follows:

 ranking = [ 'The Wall Street Journal', 'The New York Times', 'Associated Press', 'Reuters', 'Financial Times', 'USA Today','Bloomberg','CNBC']
print('Enter new coverage:')
coverage = input()
listed = coverage.split()
print(*listed, sep="\n")

Ok, so if you have the list a = [Reuters, The New York Times, The Wall Street Journal, Associated Press, Financial Times] and you want to to sort it with respect to list ranking = [ 'The Wall Street Journal', 'The New York Times', 'Associated Press', 'Reuters', 'Financial Times', 'USA Today','Bloomberg','CNBC'] you can do it by iterating through the ranking list and see if the list a has the first element of the ranking list, if it has the second and so on. The code would be something like this:

a = [Reuters, The New York Times, The Wall Street Journal, Associated Press, Financial Times]
ranking = [ 'The Wall Street Journal', 'The New York Times', 'Associated Press', 'Reuters', 'Financial Times', 'USA Today','Bloomberg','CNBC']

for element in ranking:
  for i in a:
    if i == element:
      print(i)

Result:

The Wall Street Journal
The New York Times
Associated Press
Reuters
Financial Times

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM