有没有办法查找嵌套列表中的项目是否存在?

Is there a way to find if an item in a nested list exists?

我想知道是否有办法做这样的事情 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!")

只需添加列表:

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

你很接近:

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() 以使字符串比较与大小写无关。

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

如果你真的需要使用数组的数组,你可以这样做。受 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!")