losee
losee

Reputation: 2238

How can I shuffle two object lists that I merged in my python Django app

I am trying to merge to object lists and then shuffle them but it's not working. If I use

random.shuffle(list_1)

it will shuffle that one list but if I do

first = list_1()
second = list_2()
merged = first + second
ran = random.shuffle(merged)

context = {
     "ran": ran
    }

there is no output, there is no traceback, and no error message. Is this impossible to do? these are my functions

import random

def get_vlad_tv():
    url = 'http://www.examplesite.org/'
    html = requests.get(url, headers=headers)
    soup = BeautifulSoup(html.text, "html5lib")
    divs = soup.find_all('div', {'class': 'entry-pos-1'})
    entries = [{'text': div.find('p', 'entry-title').text,
                'href': url + div.a.get('href'),
                'src': url + div.a.img.get('data-original'),
                } for div in divs][:10]

    divs_two = soup.find_all('div', {'class': 'entry-pos-2'})
    entries_two = [{'text': div.find('p', 'entry-title').text,
                'href': url + div.a.get('href'),
                'src': url + div.a.img.get('data-original'),
                } for div in divs_two][:10]

    merged = entries + entries_two

    return merged


def scrape_world():
    url = 'http://www.otherexamplesite.net'
    html = requests.get(url, headers=headers)
    soup = BeautifulSoup(html.text, 'html5lib')
    titles = soup.find_all('section', 'box')
    cleaned_titles = [title for title in titles if title.a.get('href') != 'vsubmit.php']

    entries = [{'href': url + box.a.get('href'),
                'src': box.img.get('src'),
                'text': box.strong.a.text,
                } for box in cleaned_titles]


    return entries

If it's impossible I'll just figure something else out, If it's possible point me in the right direction on how to correct my code.

Upvotes: 0

Views: 44

Answers (2)

Alvaro
Alvaro

Reputation: 12037

random.shuffle() has no return value. Check the docs here

What you can do instead is use the directly shuffled list:

first = list_1()
second = list_2()
merged = first + second
random.shuffle(merged)

context = {
    "ran": merged
}

Upvotes: 4

mng
mng

Reputation: 393

random.shuffle shuffles the list in place, it doesn't return the shuffled list.

You can do

   random.shuffle(merged)

and the list 'merged' will be shuffled, you can directly use it.

Upvotes: 2

Related Questions