是否可以找到嵌套列表中的项目是否存在?

问题描述 投票:0回答:4

我想知道是否有一种方法可以像Python这样。有什么想法吗?

inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = [inches, centimeters]
unit = input("Enter unit here... ")
if unit not in allUnits:
    print("Invalid unit!")
python nested-lists
4个回答
1
投票

只需添加列表:

inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = inches + centimeters
unit = input("Enter unit here... ")
if unit not in allUnits:
    print("Invalid unit!")

1
投票
if unit not in inches + centimeters:
    print("Invalid unit!")

1
投票

您将要关闭:

inches = ["inches", "inch", "in"]
centimeters = ["centimeters", "centimeter", "cm"]
allUnits = [*inches, *centimeters] # notice the `*`
unit = input("Enter unit here... ")
if unit.lower() not in allUnits:
    print("Invalid unit!")

应该做到这一点。

*运算符将列表展开为它们的组成元素。然后可以用来创建新列表。因此,您可以将两个列表放在一起。

我还添加了unit.lower()以使字符串比较不区分大小写。


0
投票

如果确实需要使用数组数组,则可以这样做。受C ++启发。

def isInArray(array, unit):
    for i in range(len(array)):
        for j in array[i]:
            if j == unit:
                return True;
    return False

unit = input("Enter unit here... ")
if not isInArray(allUnits, unit):
    print("Invalid unit!")
© www.soinside.com 2019 - 2024. All rights reserved.