【问题标题】:Random numbers in Python [duplicate]Python中的随机数[重复]
【发布时间】:2012-10-11 12:55:29
【问题描述】:

可能重复:
String and integer concatenation

我创建了范围从 -90 到 90 的列表。现在我需要让这个列表中的随机数出现在我的问题中。任何人都可以帮助我吗? 这是我到目前为止的地方:

latitude = [n for n in range(-90,90)]
record = latitude[random.randrange(-90,90)]
question =['lati','country']
questions = random.choice(question)

if questions == 'lati':
    resp = raw_input('Is Wroclaw north of ' + record)

当我尝试运行此程序时,我收到一条错误消息,提示我无法连接“str”和“int”对象。

【问题讨论】:

    标签: python random


    【解决方案1】:

    您不能连接字符串和数字。显示它的最佳方式是使用格式字符串,如下所示:

    resp = raw_input('Is Wroclaw north of %d' % record)
    

    【讨论】:

      【解决方案2】:

      这里需要使用str(),因为record是一个整数,所以在拼接前要先转换成字符串:

      resp = raw_input('Is Wroclaw north of ' + str(record))
      

      或使用字符串格式:

      raw_input('Is Wroclaw north of {0}'.format(record))
      

      【讨论】:

        【解决方案3】:

        在没有列表的情况下使用record = random.randrange(-90,90)。 如果你真的需要一个列表,或者下一个 construstion。

        random.choice([1,2,3])
        

        【讨论】:

          猜你喜欢
          • 2020-07-04
          • 1970-01-01
          • 2011-01-05
          • 1970-01-01
          • 2019-05-05
          • 2014-03-22
          • 2015-01-08
          • 1970-01-01
          • 2020-10-18
          相关资源
          最近更新 更多