daniel_e
daniel_e

Reputation: 257

Random Choose set of data

I have three sets of data:

item1 = 'carrot'
property1 = 'vegetable'

item2 = 'apple'
property2 = 'fruit'

item3 = 'steak'
property3 = 'meat'

And so on... Now I want to combine these to sets of data, that should be randomly chosen.

combination1 = item1 + property1
combination2 = item2 + property2
combination3 = item3 + property3

So that I can use them randomly:

random.choice(combination1, combination2, combination3)

In the end the combination has to fit in here:

Client(args.item, args.property)

Problem is, that always the set of item1+property1, item2+property2, aso. has to be taken. I can only manage to pick random combinations of items and properties, but don't know how to combine sets of them.

Can anyone help?

Upvotes: 0

Views: 68

Answers (2)

hwhite4
hwhite4

Reputation: 715

You could define a class to hold your objects data and have a list of class objects like this. This way you could easily add extra fields to your object

import random

class Food:

    def __init__(self, name, type):
        self.name = name
        self.type = type

foods = [Food('carrot', 'vegetable'), Food('apple', 'fruit'), Food('steak', 'meat')]

random_food = random.choice(foods)
print(random_food.name)
print(random_food.type)

Upvotes: 2

IMCoins
IMCoins

Reputation: 3306

import random

#   Instead of doing this...
item1 = 'carrot'
property1 = 'vegetable'

item2 = 'apple'
property2 = 'fruit'

item3 = 'steak'
property3 = 'meat'

#   You might want to do this, so you can do more general work on your data.
items = ['carrot', 'apple', 'steak']
properties = ['vegetable', 'fruit', 'meat']

#   Now if you want to choose one item from both list at random, you can do...
for _ in range(5):
    random_choice = (random.choice(items), random.choice(properties))
    print 'This is a random set of item and property : {}'.format(random_choice)

#   If you want to choose a random pair of pre-computed items, you could...
#   1.  Group your data.
combs = [(item, property) for item, property in zip(items, properties)]

#   2. Choose at random your combined data.
for _ in range(5):
    random_pair = random.choice(combs)
    print 'This is the random selected pair : {}'.format(random_pair)

Outputs :

# This is a random set of item and property : ('apple', 'fruit')
# This is a random set of item and property : ('apple', 'meat')
# This is a random set of item and property : ('steak', 'vegetable')
# This is a random set of item and property : ('apple', 'vegetable')
# This is a random set of item and property : ('apple', 'vegetable')
# This is the random selected pair : ('steak', 'meat')
# This is the random selected pair : ('steak', 'meat')
# This is the random selected pair : ('steak', 'meat')
# This is the random selected pair : ('apple', 'fruit')
# This is the random selected pair : ('apple', 'fruit')

Upvotes: 3

Related Questions