Py学习  »  Python

python列表中的count函数

emanuel • 3 年前 • 1296 次点击  

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

我的代码:

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133765
 
1296 次点击  
文章 [ 3 ]  |  最新文章 3 年前
Arun
Reply   •   1 楼
Arun    3 年前

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

Daweo
Reply   •   2 楼
Daweo    3 年前

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

lst = list(input("plase enter keyword"))

for item in lst:
    print(f"value({item})"+str(lst.count(item)))

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

Sharim Iqbal
Reply   •   3 楼
Sharim Iqbal    3 年前
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)))