Break python list into multiple lists, shuffle each lists separately [duplicate]

2024/10/13 13:16:23

Let's say I have posts in ordered list according to their date.

[<Post: 6>, <Post: 5>, <Post: 4>, <Post: 3>, <Post: 2>, <Post: 1>]

I want to break them into 3 groups, and shuffle the items inside the list accordingly.

chunks = [posts[x:x+2] for x in xrange(0, len(posts), 2)]

Now Chunks will return:

[[<Post: 6>, <Post: 5>], [<Post: 4>, <Post: 3>], [<Post: 2>, <Post: 1>]]

What are some efficient ways to randomly shuffle these items inside each respective lists? I could think of iterating through them, creating each respective lists but this seems repetitive...

I want the final output to look something like:

[[<Post: 5>, <Post: 6>], [<Post: 4>, <Post: 3>], [<Post: 1>, <Post: 2>]]

or better:

[<Post: 5>, <Post: 6>, <Post: 4>, <Post: 3>, <Post: 1>, <Post: 2>]
Answer

Sure. random.shuffle works in-place so looping through list elements and applying it on them does the first job. For the "flattening" I use a favorite trick of mine: applying sum on sublists with start element as empty list.

import random,itertoolschunks = [["Post: 6", "Post: 5"], ["Post: 4", "Post: 3"], ["Post: 2", "Post: 1"]]# shufflefor c in chunks: random.shuffle(c)# there you already have your list of lists with shuffled sub-lists
# now the flatteningprint(sum(chunks,[]))                  # or (more complex but faster below)
print(list(itertools.chain(*chunks)))  # faster than sum on big lists

Some results:

['Post: 5', 'Post: 6', 'Post: 4', 'Post: 3', 'Post: 2', 'Post: 1']
['Post: 6', 'Post: 5', 'Post: 3', 'Post: 4', 'Post: 1', 'Post: 2']

(you said you wanted something like [[<Post: 5>, <Post: 6>, <Post: 4>, <Post: 3>, <Post: 1>, <Post: 2>]] (list in a list) but I suppose that's a typo: I provide a simple, flattened list.

https://en.xdnf.cn/q/118078.html

Related Q&A

AlterField on auto generated _ptr field in migration causes FieldError

I have two models:# app1 class ParentModel(models.Model):# some fieldsNow, in another app, I have child model:# app2 from app1.models import ParentModelclass ChildModel(ParentModel):# some fields here …

How do I replace values in 2D numpy array using a dictionary of {value:(row#,column#)} pairs

import numpy as npthe array looks like so:array = np.zeros((10,10))array = [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.][ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.][ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.][ 0…

Processing items with Scrapy pipeline

Im running Scrapy from a Python script.I was told that in Scrapy, responses are built in parse()and further processed in pipeline.py. This is how my framework is set so far:Python scriptdef script(self…

How to click a button to vote with python

Im practicing with web scraping in python. Id like to press a button on a site that votes an item. Here is the code<html> <head></head> <body role="document"> <div …

Python 2.7 connection to Oracle: loosing (Polish) characters

I connect from Python 2.7 to Oracle data base. When I use:cursor.execute("SELECT column1 FROM table").fetchall()]I have got almost proper values for column1 because all Polish characters (&qu…

getting friendlist from facebook graph-api

I am trying to get users friend list from facebook Graph-api. So after getting access token when I try to open by urlopen byhttps://graph.facebook.com/facebook_id/friends?access_token=authentic_access…

Sorting Angularjs ng-repeat by date

I am relatively new to AngularJS. Could use some helpI have a table with the following info<table><tr><th><span ng-click="sortType = first_name; sortReverse = !sortReverse&quo…

Html missing when using View page source

Im trying to extract all the images from a page. I have used Mechanize Urllib and selenium to extract the Html but the part i want to extract is never there. Also when i view the page source im not abl…

Move file to a folder or make a renamed copy if it exists in the destination folder

I have a piece of code i wrote for school:import ossource = "/home/pi/lab" dest = os.environ["HOME"]for file in os.listdir(source):if file.endswith(".c")shutil.move(file,d…

Segmentation fault after removing debug printing

I have a (for me) very weird segmentation error. At first, I thought it was interference between my 4 cores due to openmp, but removing openmp from the equation is not what I want. It turns out that wh…