代码之家  ›  专栏  ›  技术社区  ›  emanuel

python列表中的count函数

  •  1
  • emanuel  · 技术社区  · 2 年前

    大家好,同志们,我想从输入中提取一个字符,并将其转换为一个列表,然后向用户显示每个索引的重复次数,但它给出了一个错误。

    我的代码:

    list = list(input("plase enter keyword"))
    
    for item in list:
        print(f"value({item})"+list.count(item))
    
    

    我的错误

    TypeError 
    Traceback (most recent call last)
    c:\Users\emanull\Desktop\test py\main.py in <cell line: 3>()
          2 list = list(input("plase enter keyword"))
          4 for item in list:
    ----> 5     print(f"value({item})"+list.count(item))
    
    TypeError: can only concatenate str (not "int") to str
    
    
    3 回复  |  直到 2 年前
        1
  •  0
  •   Sharim09    2 年前
    list_ = list(input("plase enter keyword"))
    
    for item in list_:
        print(f"value({item}) {list_.count(item)}")
    

    list_ = list(input("plase enter keyword"))
    
    for item in list_:
        print(f"value({item})"+str(list_.count(item)))
    
    
        2
  •  0
  •   Daweo    2 年前

    首先是遮蔽 list 内置是个坏主意,其次你需要把数字转换成 str 如果你想把它和其他 str ,在应用这些更改后

    lst = list(input("plase enter keyword"))
    
    for item in lst:
        print(f"value({item})"+str(lst.count(item)))
    

    但请注意,对于重复的项目,它将打印多次

        3
  •  0
  •   Arun    2 年前

    我认为出现错误的原因是,您试图将字符串和整数连接起来,这在python中是不可能的,不像javascript。因此,尝试使用str关键字将整数转换为字符串,然后连接。