Python生成指定长度的随机列表

1 投票
3 回答
3155 浏览
提问于 2025-04-17 18:42

我正在尝试写一个程序,生成一个包含10个随机整数的列表,这些整数的范围是1到5(包括1和5)。然后,我想打印出每个整数出现的次数。接着,我还想打印一个去掉重复数字的第二个列表。目前,我遇到的问题是,连第一个列表都无法生成。我一直收到一个错误提示:TypeError: 'int' object is not iterable。

这是我目前写的代码:

def randomTen():
    """return list of ten integers and the number of times each one
    appears"""
    firstList= []
    for num in range(1,11):
        x= int(random.randint(1,6))
        list1= firstList.append(x)
    print(list1)

3 个回答

0

1) x 是一个整数,不是一个列表。所以只需要使用

list1 = firstList.append(x)

2) 如果你想去掉重复的值,可以把列表转换成一个集合:

print(set(list1))
1
def randomTen():
    """return list of ten integers and the number of times each one
    appears"""
    firstList= []
    for num in range(1,11):
        x= int(random.randint(1,6))
        firstList.append(x)
    return firstList

你先创建一个空的列表,叫做firstList,然后往里面添加一些元素,最后把这个列表返回。

4

首先要注意,这个可以用列表推导式更简单地完成:

firstList = [random.randint(1,6) for num in range(1, 11)]

至于你的函数,你需要这样做:

firstList= []
for num in range(1,11):
    x= int(random.randint(1,6))
    firstList.append(x)
print(firstList)

append这个方法不会返回任何东西,它是直接在原来的列表上进行修改的。

撰写回答