Python程式:判斷字串是否包含列表中的元素


在本文中,我們將學習如何在Python中檢查字串是否包含列表中的元素。

使用的方法

  • 使用巢狀for迴圈

  • 使用列表推導式

  • 使用any()函式

  • 使用find()函式

示例

假設我們已經得到一個輸入字串和一個輸入列表。我們現在將檢查輸入字串是否包含至少一個輸入列表中的元素。

輸入

inputString = "tutorialspoint is a best learning platform for coding"
inputList = ['hello', 'tutorialspoint', 'python']

輸出

YES, the string contains elements from the input list

在上面的例子中,輸入字串包含'tutorialspoint',所以答案是yes。

方法一:使用巢狀for迴圈

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 建立一個變數來儲存輸入字串。

  • 建立另一個變數來儲存輸入列表。

  • 使用split()函式(將字串分割成列表。我們可以定義分隔符;預設分隔符是任何空格)將輸入字串分割成單詞列表。

  • 用0初始化一個臨時標誌(temp_flag)變數。

  • 使用for迴圈遍歷上述分割後的單詞列表。

  • 使用另一個巢狀for迴圈遍歷輸入列表

  • 使用if條件語句檢查兩個元素是否相等。

  • 如果條件為真,則將temp_flag設定為1。

  • 如果temp_flag變為1,則使用break語句跳出迴圈。

  • 使用if條件語句檢查temp_flag的值是否為1。

  • 列印結果

示例

下面的程式使用巢狀for迴圈檢查字串是否包含任何輸入列表元素:

# input string
inputString = "tutorialspoint is a best learning platform for coding"

# input list
inputList = ['hello', 'tutorialspoint', 'python']

# printing the input string
print("Input string:", inputString)

# printing input list
print("Input List:", inputList)

# splitting the input string into a list of words
wordsList = inputString.split(" ")

# temporary flag variable
temp_flag = 0

# traversing through the above-split words list
for p in wordsList:
   
   # traversing through the input list
   for q in inputList:
      
      # checking whether both the elements are equal
      if p == q:
         
         # Set the value of temp_flag by 1 if the condition is true
            temp_flag = 1
         
         # breaking from the loop if the temp_flag becomes 1
            break

# checking whether the value of temp_flag is 1
if temp_flag == 1:

   # printing "YES” if the condition is true
      print("YES, the string contains elements from the input list")
else:
   
   # else print "NO"
      print("NO, the string does not contain elements from the input list")

輸出

執行上述程式後,將生成以下輸出:

Input string: tutorialspoint is a best learning platform for coding
Input List: ['hello', 'tutorialspoint', 'python']
YES, the string contains elements from the input list

方法二:使用列表推導式

列表推導式

當你想基於現有列表的值構建一個新列表時,列表推導式提供了一種更短/簡潔的語法。

bool()函式 - 返回給定物件的布林值

示例

下面的程式使用列表推導式檢查輸入字串是否包含任何輸入列表元素:

# input string
inputString = "tutorialspoint is a best learning platform for coding"

# input list
inputList = ['hello', 'tutorialspoint', 'python']

# printing the input string
print("Input string:", inputString)

# printing input list
print("Input List:", inputList)
print()

# checking whether the input string contains the list element

# using list comprehension
output = [i for i in inputList if(i in inputString)]

# printing the resulting output as boolean
print("Checking whether input string contains the list element:", bool(output))

輸出

Input string: tutorialspoint is a best learning platform for coding
Input List: ['hello', 'tutorialspoint', 'python']
Checking whether input string contains the list element: True

方法三:使用any()函式

如果迭代器中的任何專案為真,則any()函式返回True,否則返回False。

語法

any(iterable)

示例

下面的程式使用any()函式檢查輸入字串是否包含任何輸入列表元素:

# input string
inputString = "tutorialspoint is a best learning platform for coding"

# input list
inputList = ['bat', 'cat', 'dog']

# printing the input string
print("Input string:", inputString)

# printing input list
print("Input List:", inputList)
print()

# checking whether the input string contains the list element

# using any() function
output = any(k in inputString for k in inputList)
print("Checking whether input string contains the list element:", bool(output))

輸出

Input string: tutorialspoint is a best learning platform for coding
Input List: ['bat', 'cat', 'dog']

Checking whether input string contains the list element: False

方法四:使用find()函式

在這個方法中,我們使用find()方法來檢視列表中是否存在該單詞;否則返回-1

find()方法

查詢給定值的第一次出現。如果找不到該值,則返回-1。

語法

string.find(value, start, end)

示例

下面的程式使用find()函式檢查輸入字串是否包含任何輸入列表元素:

# input string
inputString = "tutorialspoint is a best learning platform for coding"

# input list
inputList = ['bat', 'cat', 'dog']

# printing the input string
print("Input string:", inputString)

# printing input list
print("Input List:", inputList)
print()

# Assuming the result as False initially
reslt = False

# intilializig a variable with 0
count = 0

# travsering through the input list
for item in inputList:
   
   # checking whether the current list item is found in the string
   if(inputString.find(item) != -1):
      
      # incrementing the count value by 1 if the condition is true
      count += 1
      
# checking whether the count value is greater than or equal to 1
if(count >= 1):
   
   # assign result as True if the condition is true
   reslt = True
print("Checking whether input string contains the list element:", bool(reslt))

輸出

Input string: tutorialspoint is a best learning platform for coding
Input List: ['bat', 'cat', 'dog']

Checking whether input string contains the list element: False

結論

在本文中,我們學習了四種不同的方法來確定字串是否包含列表中的元素。此外,我們還學習瞭如何顯示布林結果,而不是使用條件語句。

更新於:2023年1月27日

瀏覽量:1K+

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告