gpt4 book ai didi

python - 匹配数字按顺序列出python

转载 作者:太空宇宙 更新时间:2023-11-04 07:26:41 24 4
gpt4 key购买 nike

我的问题是试图让两个列表按特定顺序彼此相等

例如 [1,3,5,7,4,3,2,5,7,10] == [1,3,5,7,4,3,2,5,7 ,10]

我想继续计算 10 个数字的随机列表,直到它们按特定顺序彼此相等。

我遇到的问题是如何使它们按特定顺序彼此相等?我知道我不能做硬编码数字,因为它们可以是任何地方的任何值。

我知道语句 i[] == j[] 是不正确的,那是我想使两个列表相等但不确定要放什么的地方

import random
hats = []
people = []
count = 0

while True:
for i in range(11):
hats.add(random.choice([1,2,3,4,5,6,7,8,9,10]))
for j in range(11):
people.add(random.choice([1,2,3,4,5,6,7,8,9,10]))
if(i[] == j[]):
stop == True
break
else:
count+=1
print(f'Count is {count}')

最佳答案

这样就可以了,但是你可能会坐很长时间:

import random
hats = []
people = []
count = 0
while len(hats) != 10:
k=0
while k != 10:
n = random.choice([1,2,3,4,5,6,7,8,9,10])
m = random.choice([1,2,3,4,5,6,7,8,9,10])
if(n == m):
hats.append(n)
people.append(m)
k += 1
else:
hats = []
people = []
count += 1
k=10
print(count, hats, people)

如果它们不同,我不确定您是否必须重置列表,另一种更短的方法是:

import random
hats = []
people = []
count = 0
while len(hats) != 10:
k=0
while k != 10:
n = random.choice([1,2,3,4,5,6,7,8,9,10])
m = random.choice([1,2,3,4,5,6,7,8,9,10])
if(n == m):
hats.append(n)
people.append(m)
k += 1
else:
count += 1
k=10

print(f"times: {count}", f"hats: {hats}", f"people: {people}")

输出示例:

times: 130 hats: [7, 7, 9, 5, 1, 5, 1, 7, 4, 8] people: [7, 7, 9, 5, 1, 5, 1, 7, 4, 8]

关于python - 匹配数字按顺序列出python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58194889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com