简体   繁体   中英

Python Sorting Multiple Lists Simultaneously

This is slightly different than most of the sorting questions on here and I haven't been able to figure out how to get this to work. I have 3 lists, and 2 of them I need to match the order of the 3rd list. There are integers in list 2 that correspond to the same indexed word in list 1. If there is an item in the 3rd list not in the other two i need to generate random numbers for it. The third list is also a tuple, but it's sorted so not sure that will matter. if a word is in lists are in 1 and 2 but not in 3 we can drop those.

For example:

import random

List1 = ['test', 'list', '1']
list2 = [[1,2,3], [4,5,6], [1,3,5]
list3 = [('this', 1),('is',2),('a',3),('test',4),('list',5)]

what I'd like the results to be is

list1 = ['this', 'is', 'a' , 'test', 'list'] (just equal to first item in list 3)
list2 = [random((1,4),3), random((1,4),3), random((1,4),3), [1,2,3],[4,5,6]]

Create a dictionary by zip ping the corresponding elements of list1 and list2 . Then, you can create the final list by get ting elements from that dict, or a list of random numbers if the element is not present.

>>> list1 = ['test', 'list', '1']
>>> list2 = [[1,2,3], [4,5,6], [1,3,5]]
>>> d = dict(zip(list1, list2))
>>> d
{'1': [1, 3, 5], 'list': [4, 5, 6], 'test': [1, 2, 3]}
>>> list4 = [x for x, y in list3]
>>> list5 = [d.get(x, [random.randint(1,4) for _ in range(3)]) for x in list4]
>>> list5
[[1, 2, 4], [3, 3, 1], [3, 3, 1], [1, 2, 3], [4, 5, 6]]

Some notes:

  • I renamed list1 and list2 in the output to list4 and list5 .

  • Here, same words refer to the same numbers list instance from list2 , ie if you modify one, you modify all of them. If that's not what you want, use list(d.get(...)) in the list comprehension for list5 to create new lists for each element.

  • Using get with default might be a bit wasteful here, as it creates all those lists and calls randint even if the default value is not used. Instead, you might want to use a ternary: [d[x] if x in d else [random list] for ...]

  • Both ways, if the same word appears twice in list3 that's not also in list1 , those two words will get different random numbers in list5 ; if you want the same random lists for same words, use [d.setdefault(x, [random list]) for ...]

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