如何在python列表中查找和打印特定关键字

2024-09-24 04:18:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚接触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次?即使“火腿”应该只有两次?你知道吗


Tags: 字符串代码in程序列表forindex单词
2条回答

你的代码中有一堆排印错误和缩进错误,但如果我们修复这些错误,你会遇到如下情况:

x = "ham"
y = ["hamsandwich", "ham", 2.2]
for x in y:
    print("found ham")
    print(y.index(x))

这并没有达到您期望的效果,因为for循环依次用y中的每个值覆盖原始的x变量。你知道吗

您想要的是将for更改为if,这将in从循环语法的一部分更改为运算符,检查x是否是y中的项:

x = "ham"
y = ["hamsandwich", "ham", 2.2]
if x in y:
    print("found ham")
    print(y.index(x))

这个版本的代码中没有循环,打印的索引将是1。你知道吗

如果您有兴趣在列表中找到“ham”的第一个外观,这可能有用:

x="ham"
y=["hamsanwhich", "ham",2.2]
if x in y:
    print(x," found in pos ",y.index(x))

如您所见,不需要手动迭代列表。但是,如果单词“ham”可以在列表中出现多次,并且需要查找所有位置,则可以使用enumerate

x="ham"
y=["hamsanwhich", "ham",2.2,"ham",67,2,"ham"]
for pos,element in enumerate(y):
    if element==x:
        print(x," found in pos ",pos)

如果您想要substring功能:

x="ham"
y=["hamsanwhich", "ham",2.2,"ham",67,2,"ham"]
for pos,element in enumerate(y):
    if x in str(element):
        print(x," found in pos ",pos)
        #If only interested in the first occurrence, uncomment the following line
        #break

相关问题 更多 >