只要不满足循环条件,我想继续随机生成单个字符。我希望下面的代码能够正常工作,但事实并非如此:
import string
import random
def random_characters(number):
i = 0
new_string = ''
while (i < number) :
new_string = random.choice(string.ascii_lowercase)
i = i + 1
return new_string
random_characters(3)
当我运行此代码时没有任何反应,我没有得到任何关于任何错误的反馈。我可能以错误的方式使用return new_string
,但即使这是我所缺少的,我也无法弄明白。
答案 0 :(得分:3)
首先,您的return
位于循环内部,因此您不会多次循环。将其更改为
def random_characters(number):
i = 0
new_string = ''
while (i < number) :
new_string = random.choice(string.ascii_lowercase)
i = i + 1
return new_string # <<< Dedent
random_characters(3)
#>>> 'c'
然后你需要实际构建new_string
,而不是每次都设置它。构建list
然后"".join
:
def random_characters(number):
i = 0
letters = [] # Place to put the letters
while (i < number) :
letters.append(random.choice(string.ascii_lowercase)) # <<< Add the letter
i = i + 1
return "".join(letters) # <<< Join the letters into one string
random_characters(3)
#>>> 'lgp'
然后您应该使用for i in range(number)
而不是while
循环:
def random_characters(number):
letters = []
for i in range(number): # <<< Deals with i for you.
letters.append(random.choice(string.ascii_lowercase))
return "".join(letters)
random_characters(3)
#>>> 'xay'
您可以使用带有列表理解的缩短版本:
def random_characters(number):
# MAGIC!
letters = [random.choice(string.ascii_lowercase) for i in range(number)]
return "".join(letters) # <<< Join the letters into one string
random_characters(3)
#>>> 'yby'
如果你想要运行它,你有几个选择。你可以在交互式解释器中运行它:
%~> python -i random_characters.py
>>> random_characters(3)
'zgp'
或者你可以告诉print
文件中的结果:
print(random_characters(3)) # Python 3
print random_characters(3) # Python 2
答案 1 :(得分:2)
有两个原因:
相反,请考虑:
import string
import random
def random_characters(number):
i = 0
random_chars = []
while (i < number) :
random_chars.append(random.choice(string.ascii_lowercase)) # Store the char you generate
i = i + 1
return ''.join(random_chars) # Return once you have all the characters
当然,这不是最恐怖的方式。这是一种不会在人为条件下循环的方式:
def random_characters(number):
return "".join((random.choice(string.ascii_lowercase) for _ in xrange(number)))
注意:这称为generator expression