使用Python統計匹配規則的專案


假設我們有一個數組nums,其中每個nums[i]包含三個元素[type_i, color_i, name_i]。這些描述了第i個專案的型別、顏色和名稱。我們還有一個由其他兩個字串ruleKey和ruleValue表示的規則。現在我們可以說,如果以下情況之一為真,則第i個專案與規則匹配:

  • ruleKey = "type" 且 ruleValue = type_i。

  • ruleKey = "color" 且 ruleValue = color_i。

  • ruleKey = "name" 且 ruleValue = name_i。

我們需要找到匹配的數量。

因此,如果輸入如下所示:

腳踏車藍色ElecB
汽車銀色Sumo
腳踏車藍色TVS

並且ruleKey = "color",ruleValue = "藍色",則輸出將為2,因為有兩個匹配[["腳踏車","藍色","ElecB"]和["腳踏車","藍色","TVS"]]。

為了解決這個問題,我們將遵循以下步驟:

  • count := 0

  • 如果ruleKey與"type"相同,則

    • 對於從0到專案大小的範圍內的i,執行:

      • 如果items[i, 0]與ruleValue相同,則

        • count := count + 1

  • 如果ruleKey與"color"相同,則

    • 對於從0到專案大小的範圍內的i,執行:

      • 如果items[i, 1]與ruleValue相同,則

        • count := count + 1

  • 如果ruleKey與"name"相同,則

    • 對於從0到專案大小的範圍內的i,執行:

      • 如果items[i, 2]與ruleValue相同,則

        • count := count + 1

  • 返回count

讓我們看一下下面的實現,以便更好地理解:

示例

 線上演示

def solve(items, ruleKey, ruleValue):
   count = 0
   if ruleKey == "type":
      for i in range(len(items)):
         if items[i][0] == ruleValue:
            count += 1
   if ruleKey == "color":
      for i in range(len(items)):
         if items[i][1] == ruleValue:
            count += 1
   if ruleKey == "name":
      for i in range(len(items)):
         if items[i][2] == ruleValue:
            count += 1
   return count
items = [["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]]
ruleKey = "color"
ruleValue = "blue"
print(solve(items, ruleKey, ruleValue))

輸入

[["Bike","blue","ElecB"],["Car","silver","Sumo"],["Bike","blue","TVS"]],"color",
"blue"

輸出

2

更新於:2021年5月29日

370 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告