简体   繁体   English

来自用户在 for 循环中输入的列表中最常见的数字 - Python

[英]Most common number in list from user input in for loop - Python

Here's the thing:事情是这样的:

I want to print the most common number in a list from user input in a for loop.我想从用户输入的 for 循环中打印列表中最常见的数字。 The thing is that the most common number that is returned is from the last loop, not from other inputs in the loop.问题是返回的最常见数字来自最后一个循环,而不是来自循环中的其他输入。

How can I do so?我怎么能这样做? Here's what I tried:这是我尝试过的:

import statistics
from statistics import mode

def num():
    def most_common(num):
        return (mode(num))

    grid = int(input('Number of grids: '))

    for i in range(grid):

        print('grid n°',i + 1)
        num = [int(input('1st number: ')), int(input('2nd number: ')), int(input('3rd number: '))]


    print(most_common(num))

You need to store each num you generate in a list.您需要将生成的每个num存储在列表中。 Here I've used grid_nums这里我使用了grid_nums

import statistics
from statistics import mode

def num():
    def most_common(num):
        return (mode(num))

    grid = int(input('Number of grids: '))

    grid_nums = []

    for i in range(grid):
        print('grid n°',i + 1)
        num = [int(input('1st number: ')), int(input('2nd number: ')), int(input('3rd number: '))]
        grid_nums += num


    print(most_common(grid_nums))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM