如何编写Python函数统计1000个1-10随机数中各数字的出现次数
Hey Marco, let's work through this problem together. First, let's address the bug in your current code: right now, you're looping 1000 times and generating 10 random numbers each iteration—this ends up creating 10,000 elements instead of the 1000 you need. Let's fix that, then build the counting function you're after.
Step 1: Generate a 1000-Element Random List
Instead of spitting out 10 numbers per loop, we'll generate one random number per iteration and add it to a list. We can do this cleanly with a list comprehension (or a basic loop if you prefer more visibility):
import random # Generate a list of 1000 random integers between 1 and 10 (inclusive) random_list = [random.randint(1, 10) for _ in range(1000)] # Optional: Print the list to verify (comment out if you don't need to see it) # print(random_list)
Step 2: Count Occurrences of Each Number
We have two straightforward ways to tally how many times each number 1-10 appears in the list:
Method 1: Manual Count with a Dictionary
This method gives you full control over the counting logic:
def count_occurrences(target_list): # Initialize a dictionary to track counts for every number 1-10 counts = {num: 0 for num in range(1, 11)} for num in target_list: counts[num] += 1 return counts # Get the final counts number_counts = count_occurrences(random_list) # Print the results in a readable format print("Number occurrence counts:") for num, count in number_counts.items(): print(f"Number {num}: {count} times")
Method 2: Use Python's Built-in collections.Counter
This is the more concise option—Python's Counter handles all the counting work for you:
from collections import Counter # Count occurrences in one line number_counts = Counter(random_list) # Print results (we loop through 1-10 to ensure every number is shown, even if it never appeared) print("Number occurrence counts:") for num in range(1, 11): print(f"Number {num}: {number_counts.get(num, 0)} times")
Full Working Code
Here's the combined, ready-to-run script that generates the list and outputs the counts:
import random from collections import Counter def main(): # Generate the 1000-element random list random_list = [random.randint(1, 10) for _ in range(1000)] # Count occurrences using Counter number_counts = Counter(random_list) # Display the results neatly print("=== Random List Occurrence Counts ===") for num in range(1, 11): print(f"* Number {num}: {number_counts.get(num, 0)} occurrences") if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Marco Pateno

