当前位置:首页 > Software > Python > 正文内容

列表实例

Doraemon5年前 (2020-02-21)Python5067

随机生成100个小写字母存入一个列表中,统计26个字母的出现次数。

import random
def getRandomLetter():
    code_a=ord('a')
    code_z=ord('z')
    x=random.randint(code_a,code_z)
    return chr(x)

def createList(n):
    chars=[]
    for i in range(n):
        chars.append(getRandomLetter())
        return chars

def countLetters(chars):
    counts=[0]*26
    for i in range(len(chars)):
        counts[ord(chars[i])-ord('a')]+=1
    return  counts

def main():
    chars=createList(100)
    print("The lowercase letters are:")
    for i in range (len(chars)):
        print(chars[i],end='')
    print()
    counts=countLetters(chars)
    print("The occurrences of each letters are:")
    for i in range(26):
        print(chr(i +ord('a')),':',sep='',end='')
        print(counts[i])

main()

The lowercase letters are:

c

The occurrences of each letters are:

a:0

b:0

c:1

d:0

e:0

f:0

g:0

h:0

i:0

j:0

k:0

l:0

m:0

n:0

o:0

p:0

q:0

r:0

s:0

t:0

u:0

v:0

w:0

x:0

y:0

z:0

>>> 


扫描二维码推送至手机访问。

版权声明:本文由我的FPGA发布,如需转载请注明出处。

本文链接:https://www.myfpga.cn/index.php/post/133.html

分享给朋友:
返回列表

上一篇:random库

下一篇:顺序查找

“列表实例” 的相关文章

math库的使用

math库的使用

math库包括4个数学常数math.pi      圆周率math.e       自然对数math.inf     正无穷大,负无穷大为-math.infmath.nan     非浮点数标记math库常用函数math.cell(x)      向上取整,返回不小于x的最小整数math.facto...

random库

random库

random()            生成一个[0.0,1.0)之间的随机小数randint(a,b)     生成一个[a,b]之间的整数uniform(a,b)     生成一个[a,b]之间的随机小数对random库的引用方法与math库一样,采用下面两种方式实现:import random...

顺序查找

顺序查找

如果需要查找某个特定值的位置(以便能够替换或删除它),可以直接使用index方法。searchedValue=100 #values是之前定义好的一个列表 if searchedValue in walues:     pos=values.index(searchedValue)     ...

Python自动清理错误图片,深度学习训练数据集准备

Python自动清理错误图片,深度学习训练数据集准备

使用python运行from PIL import Image from pathlib import Path import os   path = r'.'  ...

(原创)使用Python对任意网站图片进行爬取,仅用于学习

(原创)使用Python对任意网站图片进行爬取,仅用于学习

import os import time import argparse import requests import re import io from urllib.parse import ...