温馨提示×

python怎么匹配数组里的值

小亿
116
2023-11-02 23:28:36
栏目: 编程语言

在Python中,可以使用循环或列表推导式来匹配数组中的值。

  1. 使用循环:
array = [1, 2, 3, 4, 5]
value = 3

for item in array:
    if item == value:
        print("匹配到值", value)
        break
  1. 使用列表推导式:
array = [1, 2, 3, 4, 5]
value = 3

matches = [item for item in array if item == value]
if len(matches) > 0:
    print("匹配到值", value)

上述代码将匹配数组array中的值是否等于给定的value。如果匹配到值,则会打印出匹配到的值。

0