Python字符串和列表lst

img

img


从键盘输入一个字符串,分别统计数字、字母(包括大小写)和其他字符的个数,并输出每类字符及其个数。要求输出用字典形式:('字母':n1,'数字':n2,'其他':n3)
(提示:字母统计方法 isalpha (),数字统计方法isdigit0)输入样例: python is good

可以了,记得采纳一下哦!
【4】

img


lst = [int(x) for x in input().split()]  # 读取n个整数并保存到列表lst中
myset = set(lst)  # 将列表lst转换为集合myset
newlst = sorted(myset, key=lst.index)  # 对集合myset进行去重并按原顺序排序,得到新列表newlst
print(" ".join([str(x) for x in newlst]))  # 将newlst中的元素输出,以空格分隔



【5】

img

s = input()  # 从键盘输入字符串
d = {"字母": 0, "数字": 0, "其他": 0}  # 初始化字典

for c in s:
    if c.isalpha():  # 如果c是字母,则将字母计数器加1
        d["字母"] += 1
    elif c.isdigit():  # 如果c是数字,则将数字计数器加1
        d["数字"] += 1
    else:  # 否则将其他字符计数器加1
        d["其他"] += 1

print(d)  # 输出字典


4

img


5

img

  • 以下回答由chatgpt基于相关博客总结生成:

    代码如下:

    def count_chars(s):
        chars_count = {'字母': 0, '数字': 0, '其他': 0}
        for char in s:
            if char.isalpha():
                chars_count['字母'] += 1
            elif char.isdigit():
                chars_count['数字'] += 1
            else:
                chars_count['其他'] += 1
        return chars_count
    
    if __name__ == '__main__':
        s = input("请输入字符串:")
        count_dict = count_chars(s)
        print("结果为:", count_dict)
    

    运行结果:

    请输入字符串:python is good!_123
    结果为: {'字母': 10, '数字': 3, '其他': 3}
    

    具体实现思路如下:

    1. 定义一个函数count_chars,用于计算字符串中字母、数字、其他字符的个数;
    2. 函数中定义一个空字典chars_count,用于记录三类字符的个数,初始值都为0;
    3. 遍历字符串中的每个字符,使用isalpha()函数判断是否为字母,isdigit()函数判断是否为数字,其他情况默认为其他字符;
    4. 将每一类字符出现的次数记录在chars_count字典中;
    5. 返回该字典;
    6. 在主函数中,输入字符串s,调用count_chars函数得到字典count_dict;
    7. 输出结果count_dict。