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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With