Python list does not shuffle in a loop

2024/10/14 3:22:11

I'm trying to create an randomized list of keys by iterating:

import randomkeys = ['1', '2', '3', '4', '5']
random.shuffle(keys)
print keys

This works perfect. However, if I put it in a loop and capture the output:

a = []
for x in range(10):random.shuffle(keys)a.append(keys)

I am getting 10 times of the same shuffle?! Obviously something is fundamentally wrong here... Thanks in advance.

Answer

The problem is that you are shuffling the list in place and then adding the reference of the list to the combined list. Thus you end up with same list structure 10 times. "Fundamental change" is that the list has to be copied before appending it.

Here is a bit more "pythonic" way of achieving the same result with list comprehension.

import randomdef shuffleACopy(x):b = x[:] # make a copy of the keysrandom.shuffle(b) # shuffle the copyreturn b # return the copykeys = [1,2,3,4,5,6,7,8]
a = [shuffleACopy(keys) for x in range(10)]
print(a)
https://en.xdnf.cn/q/69460.html

Related Q&A

Python extract max value from nested dictionary

I have a nested dictionary of the form:{2015-01-01: {time: 8, capacity: 5}, 2015-01-02: {time: 8, capacity: 7},2015-01-03: {time: 8, capacity: 8} etc}The dictionary is created from a csv file using dic…

Exponential Decay on Python Pandas DataFrame

Im trying to efficiently compute a running sum, with exponential decay, of each column of a Pandas DataFrame. The DataFrame contains a daily score for each country in the world. The DataFrame looks lik…

TensorFlow - why doesnt this sofmax regression learn anything?

I am aiming to do big things with TensorFlow, but Im trying to start small. I have small greyscale squares (with a little noise) and I want to classify them according to their colour (e.g. 3 categories…

Extended example to understand CUDA, Numba, Cupy, etc

Mostly all examples of Numba, CuPy and etc available online are simple array additions, showing the speedup from going to cpu singles core/thread to a gpu. And commands documentations mostly lack good …

Python 2 newline tokens in tokenize module

I am using the tokenize module in Python and wonder why there are 2 different newline tokens:NEWLINE = 4 NL = 54Any examples of code that would produce both tokens would be appreciated.

Prevent encoding errors in Python

I have scripts which print out messages by the logging system or sometimes print commands. On the Windows console I get error messages likeTraceback (most recent call last):File "C:\Python32\lib\l…

How do I get the operating system name in a friendly manner using Python 2.5?

I tried:print os.nameAnd the output I got was::ntHowever, I want output more like "Windows 98", or "Linux".After suggestions in this question, I also tried:import os print os.name i…

Extend dataclass __repr__ programmatically

Suppose I have a dataclass with a set method. How do I extend the repr method so that it also updates whenever the set method is called: from dataclasses import dataclass @dataclass class State:A: int …

find least common denominator for list of fractions in python

I have a list of fractionsfrom fractions import Fractionfractions_list=[Fraction(3,14),Fraction(1,7),Fraction(9,14)]The output should be a list with the numerators for each fraction, then the denominat…

How to configure uwsgi to encode logging as json except app output

Im running uwsgi around a Python Flask webapp with these options (among others) to get JSON-encoded log records on stdout:fmt=${"timestamp": "${strftime:%FT%TZ}", "level":…