【问题标题】:Is there a way to find if an item in a nested list exists?有没有办法查找嵌套列表中的项目是否存在?
【发布时间】:2020-05-09 19:18:58
【问题描述】:

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


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

【讨论】:

  • 这可以说比列表连接更好,因为它应该更适合更大的列表
【解决方案2】:

只需添加列表:

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

【讨论】:

    【解决方案3】:
    if unit not in inches + centimeters:
        print("Invalid unit!")
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2021-07-23
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 2010-12-03
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 2021-01-02
        相关资源
        最近更新 更多