How to sort two lists (which reference each other) in the exact same way
Say I have two lists:
list1 = [3, 2, 4, 1, 1] list2 = ['three', 'two', 'four', 'one', 'one2']
If I run
list1.sort(), it'll sort it to
[1,1,2,3,4] but is there a way to get
list2 in sync as well (so I can say item
4 belongs to
'three')? So, the expected output would be:
list1 = [1, 1, 2, 3, 4] list2 = ['one', 'one2', 'two', 'three', 'four']
My problem is I have a pretty complex program that is working fine with lists but I sort of need to start referencing some data. I know this is a perfect situation for dictionaries but I'm trying to avoid dictionaries in my processing because I do need to sort the key values (if I must use dictionaries I know how to use them).
Basically the nature of this program is, the data comes in a random order (like above), I need to sort it, process it and then send out the results (order doesn't matter but users need to know which result belongs to which key). I thought about putting it in a dictionary first, then sorting list one but I would have no way of differentiating of items in the with the same value if order is not maintained (it may have an impact when communicating the results to users). So ideally, once I get the lists I would rather figure out a way to sort both lists together. Is this possible?
One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in
>>> list1 = [3,2,4,1, 1] >>> list2 = ['three', 'two', 'four', 'one', 'one2'] >>> list1, list2 = zip(*sorted(zip(list1, list2))) >>> list1 (1, 1, 2, 3, 4) >>> list2 ('one', 'one2', 'two', 'three', 'four')
These of course are no longer lists, but that's easily remedied, if it matters:
>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2)))) >>> list1 [1, 1, 2, 3, 4] >>> list2 ['one', 'one2', 'two', 'three', 'four']
It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:
>>> %timeit zip(*sorted(zip(list1, list2))) 100000 loops, best of 3: 3.3 us per loop >>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups) 100000 loops, best of 3: 2.84 us per loop
On the other hand, for larger lists, the one-line version could be faster:
>>> %timeit zip(*sorted(zip(list1, list2))) 100 loops, best of 3: 8.09 ms per loop >>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups) 100 loops, best of 3: 8.51 ms per loop
As Quantum7 points out, JSF's suggestion is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the very same DSU idiom internally for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the
zip routines are!)
I think the
zip-based approach is more flexible and is a little more readable, so I prefer it.
Python, How to sort two lists (which reference each other) in the exact same way If I run list1.sort() , it'll sort it to [1,1,2,3,4] but is there a way to get list2 in sync as well To sort rows to match another column, here is a formula can help you. 1. Select a blank cell next to the column you want to resort, for instance B1, and then enter this formula =MATCH (A1,C:C,FALSE), and drag autofill handle down to apply this formula. See screenshot:
You can sort indexes using values as keys:
indexes = range(len(list1)) indexes.sort(key=list1.__getitem__)
To get sorted lists given sorted indexes:
sorted_list1 = map(list1.__getitem__, indexes) sorted_list2 = map(list2.__getitem__, indexes)
In your case you shouldn't have
list2 but rather a single list of pairs:
data = [(3, 'three'), (2, 'two'), (4, 'four'), (1, 'one'), (1, 'one2')]
It is easy to create; it is easy to sort in Python:
data.sort() # sort using a pair as a key
Sort by the first value only:
data.sort(key=lambda pair: pair)
How to sort two lists together in Python, Is Python call by reference or call by value · Introduction to Pandas in Python Given two lists, sort the values of one list using the second list. extract the first elements of each pair from the sorted, zipped list. map the similar index of multiple containers so that they can be used just using as single entity. the other list. Then press F5 key to run this code, all sheets which have the same formatting have been sorted based on column E of each sheet in descending order at once. Note: In the above code, A:F is the data range that you want to sort, E is the column letter which you want to sort based on.
I have used the answer given by senderle for a long time until I discovered
Here is how it works.
# idx works on np.array and not lists. list1 = np.array([3,2,4,1]) list2 = np.array(["three","two","four","one"]) idx = np.argsort(list1) list1 = np.array(list1)[idx] list2 = np.array(list2)[idx]
I find this solution more intuitive, and it works really well. The perfomance:
def sorting(l1, l2): # l1 and l2 has to be numpy arrays idx = np.argsort(l1) return l1[idx], l2[idx] # list1 and list2 are np.arrays here... %timeit sorting(list1, list2) 100000 loops, best of 3: 3.53 us per loop # This works best when the lists are NOT np.array %timeit zip(*sorted(zip(list1, list2))) 100000 loops, best of 3: 2.41 us per loop # 0.01us better for np.array (I think this is negligible) %timeit tups = zip(list1, list2); tups.sort(); zip(*tups) 100000 loops, best for 3 loops: 1.96 us per loop
np.argsort isn't the fastest one, I find it easier to use.
Lists, Call sorted(iterable) with iterable as the zip object returned in the previous step to return a list of paired elements from the same indices in list1 and list2 sorted in Zip the two lists. Create a new, sorted list based on the zip using sorted(). Using a list comprehension extract the first elements of each pair from the sorted, zipped list. Concept : The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
Schwartzian transform. The built-in Python sorting is stable, so the two
1s don't cause a problem.
>>> l1 = [3, 2, 4, 1, 1] >>> l2 = ['three', 'two', 'four', 'one', 'second one'] >>> zip(*sorted(zip(l1, l2))) [(1, 1, 2, 3, 4), ('one', 'second one', 'two', 'three', 'four')]
Is it possible to sort two lists(which reference each other) in the exact , The following list contains a string, a float, an integer, and (lo!) another list: ['spam' The syntax for accessing the elements of a list is the same as for accessing the characters of a Each time through the loop i gets the index of the next element. In one case, a and b refer to two different objects that have the same value. Type =countif (List1,B1)=1 into the formula bar (optional). If you want to find and mark the cells on your second list that also appear on the first list, use this formula instead of the first one. Replace List1 with the name of your first list, and B1 with the first cell of your second list.
list1 = [3,2,4,1, 1] list2 = ['three', 'two', 'four', 'one', 'one2'] sortedRes = sorted(zip(list1, list2), key=lambda x: x) # use 0 or 1 depending on what you want to sort >>> [(1, 'one'), (1, 'one2'), (2, 'two'), (3, 'three'), (4, 'four')]
4.10 Pairs and Lists, Say I have two lists: Is it possible to sort two lists(which reference each other) in the exact same way? list1 = [3,2,4,1, 1] list2 = [three, two, four, one, one2]. You can compare two columns and sort a column to match the value in another column with formula in Excel. 1. You need to create a help column to place the matched values. Please select a blank cell in the help column, enter formula =IF (COUNTIF (B:B,A2)=0,"Missing",A2) into the Formula Bar, and then press the Enter key.
GAP (ref), Returns a list that has the same elements as lst, but in reverse order. Similar to map in the sense that proc is applied to each element of lst, but the result is that of the first application of proc producing a value other than #f, in which Returns a list sorted according to the less-than? procedure, which takes two elements I have a list of data that is not in alphabetical or numerical order. I want to sort a second list of the same date to match the first list. I cannot change the order of the data. My goal is to paste additional data from the second set back into the first data set.
array_diff - Manual, A list can be written by writing down the elements in order between square brackets [ , ] , and The term basic operation means that each other list operation can be The exact behaviour is defined in the same way as for list extractions (see 21.3). The two argument form removes the element in position pos , moving all One technique I've used for corrupted lists is to sort the list on the column in question, which brings up close spellings together, then put in the correct spelling at the top of the range of close spellings and drag it down to include all records in question, which makes them all exactly the same. Any list that requires an exact spelling
Lists, mutability, and in-place methods, Multiple occurrences in $array1 are all treated the same way. If you just need to know if two arrays' values are exactly the same (regardless of keys and order), of values and each value in one array has an exact duplicate in the other array. This cute, works by reference, and modifies the arrays deleting coincidences Click into any cell in the COLUMN you want to sort by within your list. (DO NOT highlight that column as this will sort that column only and leave the rest of your data where it is.) Click on the DATA tab. Click on either the Sort Ascending or Sort Descending button.