我刚接触python,还在学习。
我正在编写一个程序,在包含以下值的列表中查找特定单词“ham”:['hamsandwhich', 'ham', 2.2, 5]
如何编写代码以获取列表中是否存在“ham”并对其进行索引。我的代码如下,但输出很奇怪,我无法理解它说的是什么:
x="ham"
y= =["hamsanwhich", "ham",2.2]
for x in y:
print ("found ham"
y.index(x)
输出如下:
found ham
0
found ham
1
found ham
2
found ham
3
我应该逐个搜索每个子字符串吗? 为什么要索引4次?即使“火腿”应该只有两次?你知道吗
你的代码中有一堆排印错误和缩进错误,但如果我们修复这些错误,你会遇到如下情况:
这并没有达到您期望的效果,因为
for
循环依次用y
中的每个值覆盖原始的x
变量。你知道吗您想要的是将
for
更改为if
,这将in
从循环语法的一部分更改为运算符,检查x
是否是y
中的项:这个版本的代码中没有循环,打印的索引将是
1
。你知道吗如果您有兴趣在列表中找到“ham”的第一个外观,这可能有用:
如您所见,不需要手动迭代列表。但是,如果单词“ham”可以在列表中出现多次,并且需要查找所有位置,则可以使用
enumerate
:如果您想要
substring
功能:相关问题 更多 >
编程相关推荐