使用python随机模块的随机数/字母生成脚本的问题

时间:2018-01-15 19:07:05

标签: python-3.x random

所以我是一个Python初学者,我想知道是否有办法修改或修复此脚本,以便它生成随机数字/字母序列。我想我已经解决了实际的,但我需要一些关于如何将结果打印到控制台的帮助。这是我的代码:

def main():
    import random
    random.random() * 10
    myList = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    random.choice(myList)
    print(random.random() * 10 + random.choice(myList))
main()

你们中的任何人能帮助我吗?正如我之前所说,我是初学者,所以这可能是一个基本错误,答案中的例子会很棒。

编辑错误:

line 9, in main
    print(random.random() * 10 + random.choice(myList))
TypeError: unsupported operand type(s) for +: 'float' and 'str'

1 个答案:

答案 0 :(得分:1)

如果要打印浮动,请从中创建一个字符串:

def main():
    import random
    # random.random() * 10     # does nothing, you do not use the return
    myList = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o",
              "p","q","r","s","t","u","v","w","x","y","z"]
    # random.choice(myList)    # does nothing, you do not use the return
    print(str(random.random() * 10) + random.choice(myList)) 
    # prints a [0.0-1.0[ * 10 + one character

main()

您可以从使用字符串而不是列表中的常量中受益 - 并且可能希望使用其他一些函数从列表中进行绘制:

import string
import random

# prints random 20 lowercase chars w/o repeat
print(random.sample(string.ascii_lowercase,20))    # see doku for sample()

# print random 20 lowercase chars with repeat
print(random.choices(string.ascii_lowercase,k=20)) # see doku for choices()

# prints the same char multiple times
print(random.choice(string.ascii_lowercase) * random.randint(5,20))

输出:

['i', 'q', 's', 'z', 'g', 'v', 'r', 'j', 'h', 'u', 'y', 'p'
 , 'n', 't', 'k', 'c', 'm', 'a', 'x', 'd']

['f', 'x', 'u', 'x', 'a', 'l', 'f', 'u', 'l', 'x', 'j', 'i'
 , 'v', 'f', 'd', 'u', 'l', 'x', 'j', 'w']

rrrrrrrr  # this one varies in char and amounts...

Doku of random - functions宣读了samplechoicesrandom

Doku of string - constants 你的小写列表已经是一个常数。