如何在列表中显示十个过期的数字

时间:2017-12-08 19:28:36

标签: python

我之前已经问了一些关于这段代码的问题并且得到了充分的回答,但是我还有一个关于显示十个最过期的数字的问题。 (这个课程是课堂活动的一部分,我已经收到了我们所做的全部评分。我在这里发布的问题最初是在课堂上完成的,但我们在课堂上没时间了。)

#PE 8
#11-2-17



def main():
    #import data
    winninglist=get_data()


    #find frequency for lotterynumber 1-69
    frequency=find_frequency(winninglist)


    #sort the frequency
    sortedlist=sorting(frequency)

    print("The 10 most common numbers and their corresponding frequencies are: ")
    print(sortedlist[:10])

    print("The 10 least common numbers and their corresponding frequencies are: ")
    print(sortedlist[-10:])


    #find the 10 most overdue numbers

    #find the frequency of 1-69 for the regular numbers, and 1-26 for powerball



def get_data():

    #read from the file
    infile=open('power.txt','r')
    lines=infile.readlines()
    infile.close()


    #initialize winninglist
    winninglist=[]


    #processraw data line by line, taking away new character lines, split using space, add to winninglist
    for i in range(len(lines)):
        lines[i]=lines[i].rstrip('\n')
        item=lines[i].split()
        winninglist+=item



    return winninglist

def find_frequency(winninglist):
    #frequency should be a list
    frequency=[0]*69

    #count the occurance of each number

    for i in range(69):
        for item in winninglist:
            if int(item)==(i+1):
               frequency[i]+=1

    #print(frequency)
    return frequency

def sorting(frequency):

    #record both the number and frequency
    pb_frequency=[]

    for i in range(len(frequency)):
        pb_frequency.append([i+1, frequency[i]])

    #print(pb_frequency)
    #now sort using bubble sorting
    for i in range(len(pb_frequency)):
        max=i
        for j in range(i+1, (len(pb_frequency))):
            if pb_frequency[j][1]>pb_frequency[max][1]:
                max=j

        #max has the index of the highest frequency number for this round
        #we make the exchange to bubble the largest one
        temp1=pb_frequency[i][0]
        temp2=pb_frequency[i][1]
        pb_frequency[i][0]=pb_frequency[max][0]
        pb_frequency[i][1]=pb_frequency[max][1]
        pb_frequency[max][0]=temp1
        pb_frequency[max][1]=temp2
    #print(pb_frequency)
    return pb_frequency

main()

以下是txt文件的格式:

17 22 36 37 52 24

14 22 52 54 59 04

05 08 29 37 38 24

10 14 30 40 51 01 (txt文件有很多这样的数字行)

我需要帮助才能显示10个最过期的数字。每一行都有一个隐含的日期,第一行是最旧的,因此,我需要代码来显示最近发生的10个数字。我有没有看到一个简单的解决方案?

供参考,这是我的最后一个问题和答案

Can you help me fix code to show the occurrence of items in a list, for only the first five items?

1 个答案:

答案 0 :(得分:1)

from collections import Counter
input = ['your numbers in format of list']
d = {}

for i in input:
    if i in d:
        d.update({i: 1+d[i]})
    else:
        d.update({i: 1})

i = 0
l_min = []

while len(Counter(x for sublist in l_min for x in sublist)) < 11:
    i += 1
    l_min.append([k for k, v in d.items() if v == i])

print(l_min)