1
x = ['some', 'fairly', 'long', 'string']
if "fairly" in x:
    return index?

有没有一种简单的方法来获得“相当”的索引?

4

2 回答 2

4

为什么不在块中使用内置index方法try-except

lst = ["fairly","blue","car"]
x = "fairly"
try:
   print lst.index(x)
except ValueError:
   print "{0} not in list".format(x)
于 2012-11-23T18:59:20.877 回答
1

像这样的东西会起作用吗?这在单词多次出现的情况下可能会有所帮助:

In [1]: x = ['some', 'fairly', 'long', 'string', 'another', 'fairly']

In [2]: f_places = [index for index, i in enumerate(x) if i == 'fairly']

In [3]: f_places
Out[3]: [1, 5]

然后,您可以检查 usingif f_places:并相应地返回值。

于 2012-11-23T19:01:48.220 回答