我有三组数据:
item1 = 'carrot'
property1 = 'vegetable'
item2 = 'apple'
property2 = 'fruit'
item3 = 'steak'
property3 = 'meat'
等等......现在我想将这些数据组合成应该随机选择的数据集。
combination1 = item1 + property1
combination2 = item2 + property2
combination3 = item3 + property3
这样我就可以随机使用它们了:
random.choice(combination1, combination2, combination3)
最后,组合必须适合:
Client(args.item, args.property)
问题是,始终是item1 + property1,item2 + property2,aso的集合。必须采取。我只能设法挑选项目和属性的随机组合,但不知道如何组合它们。
有人可以帮忙吗?
答案 0 :(得分:3)
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)
输出:
# 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')
答案 1 :(得分:2)
您可以定义一个类来保存您的对象数据,并拥有一个类对象列表。这样,您可以轻松地向对象添加额外的字段
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)