Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在非';它没有自己的价值_Python_List_Python 3.6 - Fatal编程技术网

Python 在非';它没有自己的价值

Python 在非';它没有自己的价值,python,list,python-3.6,Python,List,Python 3.6,我试图在列表中找到一个特定的单词。听起来很简单,我和我交谈过的人都想不出答案。下面是我的问题的一个例子 list = ['this is ', 'a simple ', 'list of things.'] 我想在列表中找到单词“simple”,并记下它的位置。(本例中称为list[1]) 我尝试过几种方法,例如: try: print(list.index("simple")) except (ValueError) as e: print(e) 它将始终返回为列表中不存在的'

我试图在列表中找到一个特定的单词。听起来很简单,我和我交谈过的人都想不出答案。下面是我的问题的一个例子

list = ['this is ', 'a simple ', 'list of things.']
我想在列表中找到单词
“simple”
,并记下它的位置。(本例中称为
list[1]

我尝试过几种方法,例如:

try:
  print(list.index("simple"))
except (ValueError) as e:
    print(e)
它将始终返回为列表中不存在的
'simple'

有什么办法可以解决这个问题吗?

这是因为函数在列表中搜索精确的“简单”字符串,也就是说,它不做任何子字符串搜索。要完成任务,您可以在运算符中使用
,并对列表中的每个字符串进行比较:

my_list = ['this is ', 'a simple ', 'list of things.']


def find_string(l, word):
    for i, s in enumerate(l):
        if word in s:
            return i
    else:
        raise ValueError('"{}" is not in list'.format(word))


try:
    print(find_string(my_list, "simple"))
except ValueError as e:
    print(e)

您可以在列表中循环,检查单词是否在列表项中,并通过生成变量获取其索引。下面是一个示例代码:

list = ['this is ', 'a simple ', 'list of things.'] #our list
word = "simple"  #specific word
ind = 0  #index
for item in list: #looping through the list
    if word in item: #if the word is in the list item x
        print("'"+item+"',"+str(ind)) #printing the full word and its index separated by comma
    ind += 1 # adding 1 in index

如果找不到单词,它将不打印任何内容。

您需要迭代列表中的每个元素,然后确定单词是否在列表中。您可以定义一个函数来处理此问题:

def word_check(my_list, word):
    for i in range(0, len(my_list)):
        if word in my_list[i]:
            return i
    return False


list = ['this is ', 'a simple ', 'list of things.']

word_check(list, 'simple')

如果找到,函数将返回单词的索引,否则将返回false

相关:永远不会失败,当你在堆栈上发布溢出99/100次时,你会被[duplicate]或相关错误击中xD@ChadHendrixs然而,1/100不是绝对的。;-)