这是我想回答的问题:
这是我到目前为止所做的:
import random
def main():
number = random.randint(6, 12)
print('the number is', number)
def makelist():
numbers = random.randint(1, 100)
empty_list = []
empty_list.append(numbers)
我无法理解循环/附加部分...有人可以给我一些指导吗?感谢。
答案 0 :(得分:1)
这很有效。
&
输出:
测试1
#!/usr/bin/python
import sys, random
def makelist(number):
new_list = []
for i in range(0, number):
new_rand = random.randint(1, 100)
new_list.append(new_rand)
return new_list
def main():
number = random.randint(6, 12)
print "the number is %s" % str(number)
populated_list = makelist(number)
populated_list.sort()
for i in populated_list:
print(str(i)),
main()
测试2
the number is 11
9 11 13 17 25 33 53 61 65 85 87
测试3
the number is 8
1 14 17 23 32 49 51 81
答案 1 :(得分:1)
import random
def main():
# 1 generate random number
number = random.randint(6, 12)
# 2 call makelist
lst = makelist(number)
# 6 sort return value from makelist
lst.sort()
# 7 print values seperated by a space using for loop
for x in lst:
# for python 2
#print '%d ' % x,
print ('%d ' % x, end="")
print('')
def makelist(c):
# 3 create empty list
lst = []
# 4 use loop to append
for i in range(c):
lst.append(random.randint(1, 100))
# 5 return value
return lst
main()
你说你在第4部分遇到了麻烦。
您的目标是返回一个数字列表。所以你要做的是从空列表开始
lst = []
并循环每次向该列表附加一个值。 c
是您传递给makelist
的值,应该用作迭代循环的次数
for i in range(c):
这将迭代c
次(检查range
解释的python文档)。在每次迭代中附加一个随机整数。
lst.append(random.randint(1, 100))
你的指示是使用一个循环,但同样的事情可以通过列表理解来实现。
lst = [random.randint(1, 100) for _ in range(c)]
您可以使用_
变量名称表示您并不关心价值。
另外
lst = random.sample(range(1, 100), c)
生成随机数列表是一种更简洁的方法,但是有明确的使用循环的说明。
答案 2 :(得分:0)
import random
def makelist(count):
results = []
for i in range(0, count):
results.append(random.randint(1, 100))
return results
if __name__ == '__main__':
number = random.randint(6, 12)
print(number)
results = makelist(number)
results = sorted(results)
result_line = ''
for r in results:
result_line = result_line + '%s ' % r
print(result_line)
有更好的方法可以做到这一点,但它应该是关于你正在寻找的东西!
答案 3 :(得分:0)
这样做:
import random
def main():
number = random.randint(6, 12)
print 'the number is {0}'.format(number)
number_list = makelist(number) # return a list of "number" ints
sorted_list = sorted(number_list) # sort the list
output_string = str(sorted_list[0])
for i in range(1, number - 1):
concat = " {0}".format(str(sorted_list[i]))
output_string += concat # create the output string
print output_string
def makelist(number):
empty_list = []
for i in range(0, number): #create a list of "number" ints
rand_number = random.randint(1, 100)
empty_list.append(rand_number)
return empty_list
if __name__ == "__main__":
main()
返回:
the number is 11
21 22 26 31 33 35 50 71 75 95
答案 4 :(得分:-1)
简单的Python 3.6解决方案:
str_Key = ""
str_FullKey = ""
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64):
str_Key = random.choice(str_CharacterPool)
str_FullKey = str_FullKey + str_Key