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() 用於檢查物件或變數是否屬於指定的類或資料型別。

使用 for 迴圈和 index() 函式

在以下示例中,首先將輸入列表儲存在變數 Fruit_list 中並顯示該列表。然後使用 for 迴圈遍歷變數 i 迭代列表。接下來,將列表的型別設定為字串,這將從列表中找到字串元素。最後,使用內建函式 index() 和名為 Fruit_list 的變數顯示結果。

示例

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,該函式接受引數 'POP' 和 list_1 以查詢特定索引字串。

示例

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() 新增篩選字串。

更新於: 2023-08-16

2K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.