Hello,

If say I have 5 variables: v1=3 v2=1 v3=7 v4=6 v5=5

and two lists made from these

L1=[v1, v2, v3, v4, v5] , L2= [3, 1, 7, 6, 5]

and I sort on L2, so that I have, L2=L2.sort()=[1, 3, 5, 6, 7]

Is there a way to sort L1 so it is sorted in the same order as L2

i.e L1=[v2, v1, v5, v4, v3]

Thank you.

Recommended Answers

All 12 Replies

This does not make much sense. If you have ...

v1 = 3 
v2 = 1 
v3 = 7 
v4 = 6 
v5 = 5

mylist1 = [v1, v2, v3, v4, v5]

print(mylist1)          # [3, 1, 7, 6, 5]

print(sorted(mylist1))  # [1, 3, 5, 6, 7]

List [v1, v2, v3, v4, v5] is really synonymous to [3, 1, 7, 6, 5], so you sort the list [v1, v2, v3, v4, v5] directly.

I thought there would be a difference in sorting on a list of strings, I would get a alphabetical sort and on a list of numbers a numerical sort.
Thanks for your response.

If you want to sort list were numbers are strings you have two ways to make it work. You can right adjust the filling with blanks (see my post on high score table) or zeros or you can transform them to integers or numbers with desimals, either before putting to list or in the list by loop expression or list comprehension.

a=[3,2,7,1,2,0]
print a , '->',
a.sort()
print a ## original order lost

numlist=[]
print 'Give empty line to finish entering'

while True:
    number=raw_input('Give number: ')
    if number:
        number=int(number)
        numlist.append(number)
    else: break

print 'Sorted'
print sorted(numlist) ## sorting without changing the list

print 'Original'
print numlist
[3, 2, 7, 1, 2, 0] -> [0, 1, 2, 2, 3, 7]
Give empty line to finish entering
Give number: 32
Give number: 543
Give number: 75
Give number: -234
Give number: 43
Give number: 2
Give number: 1
Give number: 34
Give number: 
Sorted
[-234, 1, 2, 32, 34, 43, 75, 543]
Original
[32, 543, 75, -234, 43, 2, 1, 34]
>>>

Thank you Tonyjv

I thought there would be a difference in sorting on a list of strings, I would get a alphabetical sort and on a list of numbers a numerical sort.
Thanks for your response.

In your case, mylist1 = [v1, v2, v3, v4, v5] is not a list of strings. It is a list of references to values.

Hmm... Perhaps use a dictionary to sort it all?

# Original values
L1=['v1', 'v2', 'v3', 'v4', 'v5'] 
L2= [3, 1, 7, 6, 5]
# Dictionary to keep them in order
d = {}
for x in range(0, len(L2)):
    d[L2[x]] = L1[x]
# The dictionary should automatically sort by number, so your output of the dictionary is:
#{1: 'v2', 3: 'v1', 5: 'v5', 6: 'v4', 7: 'v3'}
# Now, create two new lists to store each value if you want
L11 = []
L21 = []
for x in d.items():
    L11.append(x[0])
    L22.append(x[1])

Thank you again veagaseat I did not know that and thank you hondros, I think for what I need to do your approach is most apropos in that it lends itself to the next step in my coding puzzle.

# Original values
## normal strings, not variables like ealier message
L1=['v1', 'v2', 'v3', 'v4', 'v5'] 
L2= [3, 1, 7, 6, 5] ## normal integer numbers, order index??
print L1
print L2
# Dictionary to keep them in order
d = {}
for x in range(0, len(L2)):
    d[L2[x]] = L1[x]
# The dictionary should automatically sort by number, so your output of the dictionary is:
#{1: 'v2', 3: 'v1', 5: 'v5', 6: 'v4', 7: 'v3'}
# Now, create two new lists to store each value if you want
print d
print '-'*20

L11 = []
L21 = []
for x in d.items():
    L11.append(x[0])
    L21.append(x[1]) ## WAS L22
print L11
print
print L21
print '='*40 ### MY ANSWER ###
print "Not sure what you are after, but ..."
print "You are telling that you want to sort L1 indexed by L2?"
print "zip and list comprehension:"
print "zip"
z=zip(L2,L1)
print z
print "Sort normally"
print sorted(z)
print "To only get L1, but in order of L2, we do list comprehension"
print [x[1] for x in sorted(z)] ## take to list only the index 1 components

Another approach to keep variable names and values together ...

def funk():
    v1 = 3
    v2 = 1
    v3 = 7
    v4 = 6
    v5 = 5
    # returns function's local variable dictionary
    return vars()

mydict = funk()
print(mydict)
print('-'*55)

# create (value, key) tuples and sort by value
# keeps key and value together
vk_tuple = sorted((v, k) for k, v in mydict.items())
print(vk_tuple)

"""my results -->
{'v1': 3, 'v2': 1, 'v3': 7, 'v4': 6, 'v5': 5}
-------------------------------------------------------
[(1, 'v2'), (3, 'v1'), (5, 'v5'), (6, 'v4'), (7, 'v3')]
"""

I have learned a lot studying these post, tonyvj, vegaseat many thanks.

You can mark then the thread solved?

Tony

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.