生成包含1000个随机字符的字符串,统计每个字符的出现次数,并输出出现次数最多的前10个字符及次数,用python来实现,第一行代码为import string
时间: 2024-05-30 09:14:55 浏览: 36
import string
import random
# Generate random string of length 1000
random_string = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=1000))
# Count frequency of each character
char_frequency = {}
for char in random_string:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
# Get top 10 most frequent characters
top_10_chars = sorted(char_frequency.items(), key=lambda x: -x[1])[:10]
# Print results
print("Random string:", random_string)
print("Character frequency:")
for char, frequency in char_frequency.items():
print(char, ":", frequency)
print("Top 10 most frequent characters:")
for char, frequency in top_10_chars:
print(char, ":", frequency)
阅读全文