python 如何检查一个值是否在允许列表中?

m0rkklqb  于 2022-12-17  发布在  Python
关注(0)|答案(5)|浏览(108)
exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]

如何重复exampleArray[0]中的次数,直到数组结束,该数组还检查该值是否在allowedItems中?
我已经试过了,但它不工作:

for x in exampleArray[0]:
    if exampleArray[x] in allowedItems:
        print("Valid Item")

请发送示例代码

6l7fqoea

6l7fqoea1#

for x in exampleArray:
    if x in allowedItems:
        print(f"{x} is a valid Item")
vzgqcmou

vzgqcmou2#

exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]
for x in exampleArray:
    if x in allowedItems:
        print("Valid Item: "+str(x))
    else:
        print("Invalid Item: "+str(x))

输出:-

Invalid Item: 2
Valid Item: a
Valid Item: b
aoyhnmkz

aoyhnmkz3#

# Another way: You can use set()

exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]

# Just want to know allowed list items
# intersection and '&' is same
set(allowedItems).intersection(set(exampleArray))
set(allowedItems) & set(exampleArray)

# Print allowed items list
[ print(x+' is Allowed') for x in set(allowedItems).intersection(set(exampleArray)) ]
[ print(x+' is Allowed') for x in set(allowedItems) & set(exampleArray) ]
xdnvmnnf

xdnvmnnf4#

列表理解:

exampleArray = [2, "a", "b"]
allowedItems = ["a", "b"]

[print(f"{i} is a valid Item") if i in set(allowedItems) else print(f"{i} is not a valid Item") for i in exampleArray]
xzv2uavs

xzv2uavs5#

我认为你正在努力实现这一目标。

example_array = [2, "a", "b"]
allowed_items = ["a", "b"]
for _ in range(example_array[0]):
    for item in example_array[1:]:
        if item in allowed_items:
            print(f"{item} is in allowed items")

该循环将迭代examle_array[0]次,就像上面的2次一样,然后对于每个项目,除了第一个项目(example_array[0]- 2),检查该项目是否在allowed_list中。
下面是输出:

a is in allowed list
b is in allowed list
a is in allowed list
b is in allowed list

相关问题