Python 在列表中查找包含字符串的索引

Python 在列表中查找包含字符串的索引

有时在使用Python字符串时,我们可能会遇到一种真实场景,其中对文本解析、模式匹配和从文本数据中提取特定信息可能非常有用。在Python中,我们有一些内置函数,如type()、index()、append()和isinstance(),将用于查找包含字符串的索引。

让我们以一个例子来说明:

给定输入字符串,

my_list = [108, 'Safari', 'Skybags', 20, 60, 'Aristocrat', 78, 'Raj']

输出

1, 2, 5, 7

解释

变量名称 my_list 存储包含整数和字符串混合的输入列表。最终输出结果是列表中 字符串索引 位置。

语法

示例中使用以下语法

type()

内置函数type()用于返回对象的类型。例如- 一个变量包含值4,其类型为整数。

index()

index()是Python中的内置函数,用于从列表中搜索元素并返回元素的位置。

append()

append() 是Python中的内置方法,它接受一个单一元素作为参数并将其添加到列表的末尾。

isintance()

内置函数isinstance()用于检查对象或变量是否属于指定的类或数据类型。

使用循环和index()函数

在以下示例中,通过将输入列表存储在变量Fruit_list中并显示列表来开始程序。然后使用for循环和变量i迭代列表。接下来,将列表的类型设置为字符串,以从列表中找到字符串元素。最后,使用带有名为Fruit_list的变量的内置函数index()显示结果。

示例

Fruit_list = ['Banana', 'Apple', 1000, 'Mango']
print("String present in the index:\n")
# iterate through the list of elements
for i in Fruit_list:
# check for type is str
    if type(i) is str:
# display index
        print(Fruit_list.index(i))

输出

String present in the index:

0
1
3

具体字符串搜索以查找索引

在以下示例中,我们将首先定义一个名为all_index()的函数,它接受两个参数- value(接收指定的字符串)和qlist(接收列表项)。该函数使用while循环重复调用列表的index方法以在列表中查找value的下一个出现。如果找到一个出现,它的索引将被添加到ids列表中。如果不再找到更多的出现,将抛出并捕获一个ValueError,并退出循环。最后,返回索引列表。程序使用递归函数设置输入列表,并借助index()和append()函数找到所有相同字符串的索引。

示例

def all_index(value, qlist):
    ids = []
    idx = -1
    while True:
        try:
            idx = qlist.index(value, idx+1)
            ids.append(idx)
        except ValueError:
            break
    return ids
print("Specific search on string index:")
all_index("Obm", ["Obm","Abc","Obm","Abm","Obm"])

输出

Specific search on string index:
[0, 2, 4]

使用index()函数

在以下示例中,通过将输入列表存储在变量list_1中启动程序。然后使用print函数设置打印语句。接下来,它将使用内置的index函数,并使用list_1作为参数,找到特定索引字符串为’POP’。

示例

list_1 = ['PUSH', 'TOP','POP']
print("The following index is:")
list_1.index('POP')

输出

The following index is:
2

使用isinstance()函数

在以下示例中,首先通过创建列表并将其存储在变量list1中来开始程序,并显示列表。然后将变量inx初始化为0,指示列表中的第一个元素,并帮助在while循环中迭代。使用while循环,它将基于列表索引检查条件。然后使用内置函数isinstance(),它接受参数list[inx]和str来查找对象类型,以返回指定的字符串索引。

示例

# create the list containing both string and integer
list1 = ['Vivek', 198, 200, 'Jayant', 'deep', 78]
# display list1
print("The original list:", list1)
# initialize index variable
inx = 0
# iterate through the list of elements using a while loop
print("The following string index:")
while inx < len(list1):
# check for type is str
    if isinstance(list1[inx], str):
# display the index
        print(inx)
# increment the index
    inx += 1

输出

The original list: ['Vivek', 198, 200, 'Jayant', 'deep', 78]
The following string index:
0
3
4

结论

我们讨论了解决问题陈述的各种方法。像for和while这样的循环对于在列表中进行迭代并使用条件找到特定索引很有帮助。内置函数index()返回列表中字符串的特定位置,并使用append()添加过滤字符串。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程