[英]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.