将Randint数字放入字典中

-2 投票
1 回答
1658 浏览
提问于 2025-04-18 05:26

可以把用random.randint生成的随机数加到字典里吗?还是说把它加到列表里更好?我问这个是因为我想得到一个随机数random.randint(0,100),然后检查这个随机数在列表或字典中是否已经存在,如果存在的话,就打印出第二个相同数字的位置。

我已经尝试过把它加到字典里,但那样不行!

编辑

import random
randomdict = {}
numbposition = {}
def randomnumber(numb):

    for i in random.randint(0,numb+1):
        randomdict.append(i)
        if i in randomdict:
            numbposition.index(i)
            print (numbposition)
            print (randomdict)
while True:
    numb = int(input('Give me number: '))
    print(randomnumber(numb))
    break

1 个回答

0

当然可以把 random.randint 返回的值添加到字典或列表中;它只是一个整数,可以像其他任何数字一样处理。不过,你不能对字典使用 append,这个语法是用来在列表的末尾添加新元素的。要往字典里添加新内容,应该用 d[key] = value。另外,字典没有像列表和元组那样的索引;它们只有键,没有固定的顺序。

这里有一个接近你描述的例子:

import random

l = []
for _ in range(10):
    n = random.randint(0, 10)
    print(n)
    if n not in l:
        print("New item.")
        l.append(n)
    else:
        print("Item found at index {0}.".format(l.index(n)))
print(l)

这个例子的输出是:

2
New item.
2
Item found at index 0.
2
Item found at index 0.
1
New item.
3
New item.
10
New item.
6
New item.
4
New item.
4
Item found at index 5.
10
Item found at index 3.
[2, 1, 3, 10, 6, 4]

编辑

如果你想把所有数字加起来并找到最大的已有索引,你需要稍微调整一下:

if n not in l:
    print("New item.")
else:
    index = max(i for i, v in enumerate(l) if v == n)
    print("Item found at index {0}.".format(index))
l.append(n)

注意,append 被移到了最后(这样在寻找最大的已有索引时,新加的 n 不会在列表中),而且我们不能再使用 list.index(这个方法找到的是第一个索引)——这需要更复杂的计算。

这样就可以得到:

0
New item.
4
New item.
10
New item.
10
Item found at index 2.
3
New item.
4
Item found at index 1.
1
New item.
8
New item.
8
Item found at index 7.
1
Item found at index 6.
[0, 4, 10, 10, 3, 4, 1, 8, 8, 1]

撰写回答