如何使循环重复多次 - Python 3

时间:2014-01-27 02:43:05

标签: python python-3.x

我2周前开始编程是我生命中的第一次,我遇到了一些我无法弄清楚的东西。我试图让它如此循环,从一组设定的随机数计算中位数可以重复多次(比如10,000),同时将所有中间值存储到一个列表中。我已经拥有了从计算中位数(listMedian)的随机整数(numbList)创建列表的所有内容。我希望能够在生成所有计算中位数的列表时多次重复此过程。样本大小是每个列表的数量,上限决定了每个单独数字的范围,谢谢!我使用的是Python 3。

import random


def median(numbList):

    srtd = sorted(numbList)
    mid = len(numbList)//2
    if len(numbList) % 2 == 0:
        return (srtd[mid-1] + srtd[mid]) / 2.0
    else:
        return srtd[mid]


sampleSize = int(input("What is your desired sample size? "))

upperLimit = int(input("What is your desired upper limit? "))

numbList = []

totalMedians = []

biggerList = []


while sampleSize > 0:

    sampleSize -= 1

    randomNum = random.randrange(0,upperLimit+1)

    numbList.append(randomNum)

    numbList.sort(key=int)

    listMedian = median(numbList)

2 个答案:

答案 0 :(得分:1)

以下是您想要的简单示例:

#!/usr/bin/python

import random

def create_list(sampleSize, upperLimit):
    numbList = []
    while sampleSize > 0:
        sampleSize -= 1
        randomNum = random.randrange(0,upperLimit+1)
        numbList.append(randomNum)
    numbList.sort(key=int)
    return numbList

def median(numList):
    list_len = len(numList)
    if list_len % 2:
        return numList[list_len / 2]
    else:
        return (numList[list_len / 2] + numList[list_len / 2 - 1]) / 2.0

def main():
    number_lists = 4
    sample_size = 5
    upper_limit = 50
    lists = []
    median_list = []

    for i in range(number_lists):
        lists.append(create_list(sample_size, upper_limit))

    for current_list in lists:
        current_median = median(current_list)
        print current_list, " : median (", current_median, ")"
        median_list.append(current_median)

    print "Median list is ", median_list

if __name__ == "__main__":
    main()

输出,例如:

paul@MacBook:~/Documents/src/scratch$ ./sample.py
[3, 18, 20, 26, 46]  : median ( 20 )
[18, 22, 38, 44, 49]  : median ( 38 )
[28, 29, 34, 42, 43]  : median ( 34 )
[4, 21, 27, 31, 46]  : median ( 27 )
Median list is  [20, 38, 34, 27]
paul@MacBook:~/Documents/src/scratch$ 

答案 1 :(得分:0)

说你有这个

print ('hello')

要循环它,你需要添加:for #1 in range(#2):在开始时(#1任何变量,#2重复多少次)

例如

for somevariable in range(3)
print('hello')

hello
hello
hello