Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-Order a list so that X follows Y and Y follows X

Tags:

python

django

So I am using the python chain method to combine two querysets (lists) in django like this.

results=list(chain(data,tweets[:5]))

Where data and tweets are two separate lists. I now have a "results" list with both data and tweet objects that I want ordered in this fashion.

results=[data,tweets,data,tweets,data,tweets]

What is the best way to achieve this kind of ordering? I tried using random.shuffle but this isnt what I want.

like image 858
cj ogbuehi Avatar asked Jun 27 '13 20:06

cj ogbuehi


People also ask

What is sorted () in Python?

The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.

How do you sort a list in custom order in Python?

Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.

How do I sort a list with another list?

Approach : 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.


1 Answers

You can use itertools.chain.from_iterable and zip:

>>> data = [1,2,3,4] 
>>> tweets = ['a','b','c','d']
>>> list(chain.from_iterable(zip(data,tweets)))
[1, 'a', 2, 'b', 3, 'c', 4, 'd']

Use itertools.izip for memory efficient solution.

like image 98
Ashwini Chaudhary Avatar answered Nov 14 '22 23:11

Ashwini Chaudhary