【问题标题】:python generating random lists of defined lengthpython生成定义长度的随机列表
【发布时间】:2013-03-11 23:44:07
【问题描述】:

我正在尝试编写一个程序,该程序生成一个包含 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)

【问题讨论】:

  • 你想要append,而不是extend
  • 谢谢。我改变了它,但现在它只返回“无”
  • 是的,这就是 append() 的工作原理。它更改源列表(“firstList”)并且不返回任何内容。
  • 此外,您的函数将继续返回 None,直到您返回带有 return 关键字的内容。
  • 也就是说,像firstList = [random.randint(1,6) for num in range(10)] 这样的列表理解是一种更“pythonic”的方式来做同样的事情。

标签: python


【解决方案1】:

首先请注意,这可以通过列表推导更轻松地完成:

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 不返回任何内容,它会更改列表。

【讨论】:

  • 不应该 randint(1,6)randint(1,5) 吗?来自 OP:“包含 1-5 的十个随机整数的列表
  • @Robᵩ:我是按照 OP 的说法,但你肯定是对的!
【解决方案2】:
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

首先创建一个空列表,将元素附加到它,然后返回它。

【讨论】:

    【解决方案3】:

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

    list1 = firstList.append(x)
    

    2) 如果您想删除重复,您可能只想将列表转换为集合:

    print(set(list1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 2012-05-16
      • 2016-02-16
      • 2016-04-01
      相关资源
      最近更新 更多