Showing posts with label Shuffle. Show all posts
Showing posts with label Shuffle. Show all posts

3/14/2023

python dict shuffle

shuffle dict order 


.

import random

my_dict = {'apple': 2, 'banana': 3, 'orange': 1, 'kiwi': 4}

# Convert the dictionary to a list of tuples and shuffle it
items = list(my_dict.items())
random.shuffle(items)

# Convert the shuffled list back to a dictionary
shuffled_dict = {k: v for k, v in items}

print(shuffled_dict)

..


Thank you.


5/11/2022

python dict order shuffle

 


..

import random
d = {'a':1, 'b':2, 'c':3, 'd':4}
l = list(d.items())
random.shuffle(l)
d = dict(l)
print(d)

..

{'a': 1, 'c': 3, 'b': 2, 'd': 4}




3/11/2020

shuffle two related list python

method #1
..
a=['aaaaa','bbbb','cccc','dddd']
b=[1, 2, 3, 4]

from sklearn.utils import shuffle
list_1, list_2 = shuffle(a, b)
print(list_1, list_2)
#['cccc', 'aaaaa', 'dddd', 'bbbb'] [3, 1, 4, 2]
..

method #2
...
list1_shuf = []
list2_shuf = []
index_shuf = list(range(len(a)))
shuffle(index_shuf)
for i in index_shuf:
list1_shuf.append(a[i])
list2_shuf.append(b[i])

print(list1_shuf)
print(list2_shuf)
#['cccc', 'aaaaa', 'bbbb', 'dddd']
#[3, 1, 2, 4]
...



6/20/2016

Matlab vector index shuffle


V1 =[ 10 20 30 40 50 60 70];
V2 = V1( :, randperm( length(V1) ));

V2 =

     60    10    20    30    50    40    70

7/29/2014

no duplication random, (stl random_shuffle example source code)

sometimes, we need no duplication random sequence data.
simple method is using shuffle random in stl.

refer to this source code.

#include < stdio.h>
#include < vector>
#include < algorithm>
#include < cstdlib>
#include < ctime>
#include < iostream>
using namespace std;


void main()
{
 //set size and initialize
 vector< int > A(10);
 for(int i=0; i< A.size(); ++i)
  A[i] = i;

 //confirm
 printf("----origin data \n");
 for(int i=0; i< A.size(); ++i)
  printf("[%d] - %d \n", i, A[i] );
 printf("----\n");

 //random 
 srand( unsigned (time(0) ) );
 random_shuffle( A.begin(), A.end() );

 //confirm
 printf("---- After shuffle \n");
 for(int i=0; i< A.size(); ++i)
  printf("[%d] - %d \n", i, A[i] );
 printf("----\n");
}


..