使用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
广告