我的目标是能够生成由 3 个变量组成的随机元组。2 是 float(x,y 坐标),最后一个是字符串。每个元组的格式应该是 (float, float, string)。我很确定 x,y 很简单,但我不确定是否可以生成一个字符串作为第三个参数。字符串应该是一个集合内的随机选择。例如,假设我有一个字符串列表["one", "two" , "three"]。我希望我生成的元组由两个随机浮点数和该集合中的一个字符串组成。我在想类似于下面这个代码的东西[(randint(0, 180), randint(0, 180)) for _ in range(100)]再次澄清我只是想弄清楚是否有可能将集合中的字符串添加为我的元组中的第三个变量
3 回答

慕姐4208626
TA贡献1852条经验 获得超7个赞
使用random.choice
import random
strings = ['one', 'two', 'three']
[(random.randint(0, 180), random.randint(0, 180), random.choice(strings)) for _ in range(100)]

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
[(randint(0, 180), randint(0, 180)) for _ in range(100)]
这不会生成随机浮点数,而是生成随机整数,如函数名称所示。反而:
[(uniform(0, 180), uniform(0, 180), choice(["one,"two","three"]) for _ in range(100)]
笔记:
random.uniform 生成范围内的随机浮点数(0,180)
random.choice 从 ["one","two","three"] 中随机选择一个元素

守着一只汪
TA贡献1872条经验 获得超3个赞
您可以获得字符串列表索引的随机数,并使用它来获取随机字符串
list_of_strings = ["one", "two" , "three"]
print [(randint(0, 180), randint(0, 180), list_of_strings[randint(0, len(list_of_strings) -1 )]) for _ in range(100)]
添加回答
举报
0/150
提交
取消