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

时间:2015-04-22 22:07:37

标签: python list element

我有一个列表,我想查看字符串" Monday"是在它,但我想知道,如果它是什么列表的元素是什么?

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

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

您可以尝试使用enumerate()功能:

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

这将为您提供变量“星期一”的索引位置,在此实例中,项目列表中的任何位置 - 考虑到它可能列在多个位置。

答案 2 :(得分:0)

如果我们正在搜索“b”:

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

将考虑多个外观并将所有这些的索引作为列表

以上内容返回:[1, 2]