简体   繁体   English

检查列表中的哪个元素具有我要搜索的字符串

[英]Checking what element in the list has the string I am searching for

I have a list, I want to check whether the string "Monday" is in it, but I want to know, if it is then what element of the list is it in? 我有一个列表,我想检查其中是否包含字符串“ Monday”,但是我想知道,如果它是列表中的哪个元素?

    list1 = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
if "Monday" in list1:
    print("True")
list1 = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
if "Monday" in list1:
    print(list1.index("Monday"))

You can try using the enumerate() function as such: 您可以尝试如下使用enumerate()函数:

for i, j in enumerate(["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]):
    if j == 'Monday':
        print i

This will give you the index location of the variable "Monday," in this instance, wherever in the list the item is - taking into account that it might be listed in multiple locations. 在这种情况下,这将为您提供变量“星期一”的索引位置,无论该项目在列表中的任何位置-考虑到它可能在多个位置列出。

If we are searching for "b": 如果我们要搜索“ b”:

[x for x,y in enumerate(["a","b","b","c","d","e","f","g"]) if "b" in y]

Will account for multiple appearances and give the indexes of all of them as a list 将考虑多个外观并将所有索引显示为列表

the above returns as: [1, 2] 上面的返回为: [1, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查列表中字符串的最后一个元素 - Checking last element of a string in a list 如果我将列表中的字符串与字符串变量进行比较,它是检查单词中的所有字符还是检查列表中的单词本身 - If i am comparing a string in a list to a string variable, is it checking all the characters in the word or the word itself on the list 我正在搜索元组列表中的3个字符串 - I am searching a list of tuples for 3 strings 使用Python检查列表中是否存在字符串元素? - Checking if string element is present in a list with Python? 在Python中的列表中搜索某个元素和元素中的字符串 - Searching a list in Python for a certain element and string inside element 在列表列表中搜索元素 - searching an element in list of list 在列表中搜索字母时,它总是给我两个或更多的输出。 我该如何解决这个问题?我想念什么? - when searching for a letter in a list, its gives me always two output or more. how do i fix this and what am i missing? 我无法在 python 的嵌套列表中找到重复的元素。 如果有人有最好的解决方案? - I am unable to find repeated element in nested list in python. If anyone has best solution? 搜索一个孤立的列表元素 - Searching for an isolated list element 在列表列表中搜索元素 - Searching for an element in list of lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM