如何从for循环内的列表中获得唯一的随机值?



我制作了一个脚本,将来自2个不同csv文件的数据组合在一起,生成一个不同行(提示符)的txt文件。我想做的是避免重复同样的"结尾"变量,使所有提示符都不同。

这个脚本完成了我所需要的,但是它显然重复了一些值,因为ran是一个随机数。

我无法避免重复相同的随机数,因为随机数在多列中使用。为每个列创建一个不同的变量可以解决这个问题,但是列数很高,甚至可能随着时间的推移而改变。

另一种选择是从"asstag"中删除元素。列表一旦被使用,但是列表是在for循环中生成的,我不知道如何从列表中删除元素,而for循环正在迭代它。

输入:

people = {'Name' : ['mark', 'bill', 'tim', 'frank'],
'Tag' : [color, animal, clothes, animal]}
dic = {'color' : ['blu', 'green', 'red', 'yellow'],
'animal' : [dog, cat, horse, shark],
'clothes' : [gloves, shoes, shirt, socks]}

预期输出:

mark blu (or green, or red, or yellow)
bill horse (or dog, or cat, or shark)
tim socks (or gloves, or shoes, or shirt)
frank dog (or cat, or shark, but not horse if horse is already assigned to bill)

代码:

people = pd.read_csv("people.csv")
dic = pd.read_csv("dic.csv")
nam = list(people.loc[:,"Name"])    
tag = list(people.loc[:,"Tag"])
with open("test.txt", "w+") as file:  
for n, t in zip (nam, tag):
asstag = list(dic.loc[:, t])
ran = random.randint(0, len(dic.loc[:, tag]) - 1)
fintag = asstag[ran]
prompt = (str(nam) + " " + str(fintag))
print(prompt)
file.write(prompt)

根据标签选择唯一元素的一种方法,使用random.sample:

import pandas as pd
import random
from collections import Counter
random.seed(42)
people = pd.DataFrame({'Name': ['mark', 'bill', 'tim', 'frank'],
'Tag': ['color', 'animal', 'clothes', 'animal']})
dic = pd.DataFrame({'color': ['blu', 'green', 'red', 'yellow'],
'animal': ['dog', 'cat', 'horse', 'shark'],
'clothes': ['gloves', 'shoes', 'shirt', 'socks']})
names = list(people.loc[:, "Name"])
tags = list(people.loc[:, "Tag"])
samples_by_tag = {tag: random.sample(dic.loc[:, tag].unique().tolist(), count) for tag, count in Counter(tags).items()}
for name, tag in zip(names, tags):
print(name, samples_by_tag[tag].pop())

mark blu
bill horse
tim shirt
frank dog

这个想法是通过使用random.sample的每个标签来采样n_i唯一元素,其中n_itags中每个tag出现的数字,这是在行中完成的:

samples_by_tag = {tag: random.sample(dic.loc[:, tag].unique().tolist(), count) for tag, count in Counter(tags).items()}

对于给定的运行,它可以取以下值:

{'color': ['blu'], 'animal': ['dog', 'horse'], 'clothes': ['shirt']}
# samples_by_tag 

注意你需要删除:

random.seed(42)

使脚本每次都给出随机结果。参见random.seed的文档和关于可重复性的说明。

如果一个标签的值比需要的少,并且您有一个列表来替换它们,请执行以下操作:

other_colors = ['black', 'violet', 'green', 'brown']
populations = { tag : dic.loc[:, tag].unique().tolist() for tag in set(tags) }
populations["color"] = list(set(other_colors))
samples_by_tag = {tag: random.sample(populations[tag], count) for tag, count in Counter(tags).items()}
for name, tag in zip(names, tags):
print(name, samples_by_tag[tag].pop())

最新更新