Python Order a list, so X follows Y and Y follows X

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

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

If data and tweets are two separate lists. Now I have a list of β€œresults” with data and tweet objects that I want to order in this way.

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

What is the best way to achieve such an order? I tried using random.shuffle, but that is not what I want.

+7
source share
3 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 an efficient memory solution.

+6
source

Here's a solution using iterators:

 from itertools import izip result = (v for t in izip(data, tweets) for v in t) 
+5
source

You can do it as follows:

 >>> result = [None]*(len(data)+len(tweets)) >>> result[::2] = data >>> result[1::2] = tweets 
+2
source

All Articles