Python - 檢查列表是否包含特定數字


當需要檢查列表是否包含特定數字時,將使用 `join` 方法和一個簡單的迭代。

示例

以下是相同內容的演示

my_list = [415, 133, 145, 451, 154]

print("The list is :")
print(my_list)
my_digits = [1, 4, 5, 3]

digit_string = ''.join([str(ele) for ele in my_digits])
all_elems = ''.join([str(ele) for ele in my_list])

my_result = True
for element in all_elems:

   for ele in element:
      if ele not in digit_string:
         my_result = False
         break

if(my_result == True):
   print("All elements have been made from required digits")
else:
   print("All elements haven't been made from required digits")

輸出

The list is :
[415, 133, 145, 451, 154]
All elements have been made from required digits

說明

  • 定義了一個列表並顯示在控制檯上。

  • 定義了另一個包含整數的列表。

  • 列表解析用於遍歷第二個列表並將其連線起來。

  • 這被分配給一個變數。

  • 使用另一個列表解析來遍歷第一個列表並將其連線起來。

  • 這被分配給另一個變數。

  • 另一個結果變數最初被分配為“True”。

  • 遍歷第二個變數,如果在第一個變數中找不到,則將結果變數分配為“False”。

  • 如果在退出條件後結果仍然為“True”,則將在控制檯上顯示相關訊息。

更新於: 15-Sep-2021

273 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.