如果列表中有任何"单词",请打印带有单词(python)的列表索引


#input list
lst = ['abc', 'def', 'ghi','python', 'pool']

if any(word in lst for word in ('def', 'kok', 'python')):
print(lst.index(word))
else:
print("string is not present")

因为单词'def'和'python'在list[1]和list[3]中。输出应该是:

1

3

但是我得到…NameError:名称"word"没有定义。我如何让它打印出想要的结果?

any语句只返回一个布尔值,你不能再使用给它的东西了。那么您可以理解lst.index(word)将给出一个值,而不是:存在的所有单词的索引

计算当前单词的索引列表,如果有的话打印它们,或者打印else字符串

lst = ['abc', 'def', 'ghi', 'python', 'pool']
indexes = [lst.index(word) for word in ('def', 'kok', 'python') if word in lst]
if indexes:  
print(*indexes)
else:
print("string is not present")

不要使用"any"功能:

lst = ['abc', 'def', 'ghi','python', 'pool']
for word in ('def', 'kok', 'python'):
if word in lst:
print(lst.index(word))
else:
print("string is not present")

可以避免在for循环中使用推导式:

lst = ['abc', 'def', 'ghi','python', 'pool']
out = []
for word in ('def', 'kok', 'python'):
if word in lst:
out.append(word)
print(f"string {word} is present on index {lst.index(word)}")
else:
print(f"string {word} is not present")

输出:

string def is present on index 1
string kok is not present
string python is present on index 3

这也可以通过设置交集来实现。

你想知道列表ref中的字符串是否存在于列表lst所以…

lst = ['abc', 'def', 'ghi','python', 'pool']
ref = ['def', 'kok', 'python']
if c := set(lst).intersection(set(ref)):
print(*(lst.index(k) for k in c), sep='n')
else:
print('string not present')

如果两个列表中没有相同的字符串,相交将返回一个空集合。在这种特殊情况下,该集合将包含两个值-即{'def','python'}

输出:

1
3