【问题标题】:Find a individual word location in a list that isn't its own value在列表中查找不是其自身值的单个单词位置
【发布时间】:2018-08-11 07:02:38
【问题描述】:

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

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

我想在列表中找到单词"simple",并记下它的位置。 (在这个例子中又名list[1]。)

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

try:
  print(list.index("simple"))
except (ValueError) as e:
    print(e)

因为'simple' 不在列表中,所以总是会返回。

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

【问题讨论】:

标签: python list python-3.6


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    您需要遍历列表中的每个元素,并确定您的单词是否在列表中。你可以定义一个函数来处理这个:

    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。

    【讨论】:

      【解决方案3】:

      您可以遍历列表并检查单词是否在列表项中并通过创建变量来获取其索引。这是一个示例代码:

      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
      

      如果找不到该单词,则不会打印任何内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-20
        • 2015-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-03
        相关资源
        最近更新 更多