所以我在Python中有两个列表:
import random
list_1 = ['1','2','3']
list_2 = ['4','5','6']
num = random.choice(list_1 or list_2)这似乎不管用。如何从列表1或列表2中获取随机数?
发布于 2018-11-25 00:33:54
您可以连接以下列表:
num = random.choice(list_1 + list_2)或者选择一个列表,然后选择一个字符:
num = random.choice(random.choice([list_1],[list_2]))发布于 2020-02-20 11:33:34
不短,但可以作为参考。
import random
name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','man','shopping','pen','mouse']
population = list(zip(name, second))
ox_list = []
for a in range(20):
samples = random.sample(population, 1)
samples = str(samples).strip('[]')
ox_list.append(samples.replace("', '", ''))
for o in set(ox_list):
print (o.replace("')",'').replace("('",''))
I have lemon
I want cat
I love banana
I like man
I buy soap
I hate water
I see shopping发布于 2021-07-15 22:14:40
使用random.sample从两个列表中进行选择。如果你只想从一个列表或另一个列表中进行选择,你可以使用mod %来反转偶数和奇数,其中一个列表是偶数,一个列表是奇数,然后随机采样。
name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','woman','shopping','pen','mouse']
result=[]
for i in range(10):
a=random.sample(name,1)
b=random.sample(second,1)
result.append(a[0]+ b[0])
print(result)
#[result.append(random.sample(name,1)[0]+random.sample(second,1)[0]) for i in
range(10)]
print(result)输出:
['I buy pen', 'I buy cat', 'I like woman', 'I have water', 'I hate water', 'I want water', 'I buy water', 'I see banana', 'I love woman', 'I buy woman']在两个列表之间随机切换
result=[]
for i in range(10):
a_num=random.sample(range(10000),1)
if a_num[0]%2:
result.append(random.sample(name,1))
else:
result.append(random.sample(second,1))
print(result)输出:
[['mouse'], ['I see '], ['banana'], ['cat'], ['I buy '], ['soap'], ['woman'], ['I like '], ['soap'], ['cat']]https://stackoverflow.com/questions/53460095
复制相似问题