我想知道是否有一种方法可以像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!")
if unit not in inches + centimeters:
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()
以使字符串比较不区分大小写。
如果确实需要使用数组数组,则可以这样做。受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!")