Python随机选择在每个循环迭代中返回相同的结果

2024-09-28 13:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道为什么当我运行这段代码时,会将同一个字典条目追加100次吗

from random import choice

aliens = []
alien = {}

colors = ['red', 'blue', 'green', 'black', 'purple', 'brown', 'yellow', 'coral']
points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
speeds = ['slow', 'medium', 'fast']

for i in range(1,101):
    alien['color'] = choice(colors)
    alien['points'] = choice(points)
    alien['speed'] = choice(speeds)
    aliens.append(alien)

print(aliens)

Tags: 代码fromimport字典条目randomgreenblue
1条回答
网友
1楼 · 发布于 2024-09-28 13:13:08

该链接存储字典和列表,并将其添加到另一个列表中,您只需创建指向同一字典的新链接。只需使用alien.copy()

from random import choice

aliens = []
alien = {}

colors = ['red', 'blue', 'green', 'black', 'purple', 'brown', 'yellow', 'coral']
points = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
speeds = ['slow', 'medium', 'fast']

for i in range(1,101):
    alien['color'] = choice(colors)
    alien['points'] = choice(points)
    alien['speed'] = choice(speeds)
    aliens.append(alien.copy())

print(aliens)

相关问题 更多 >

    热门问题