首页 > 解决方案 > 如何检查某物是否在列表中的整数中

问题描述

这是我的一些代码:(我通过为每个变量选择一个随机数来定义列表“板条箱”中的变量)

crates = [one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twentyone, twentytwo, twentythree, twentyfour, twentyfive, twentysix]

choicecrate = int(input("Which crate do you think is your lucky crate? "))

#insert figuring out if 'choicecrate' is 1, 2, 3, 4, etc. then removing it from the list

我正在尝试检查用户输入的数字是否是“板条箱”列表中变量的数字写入。我该怎么做呢?例如,人输入数字 17,我需要让计算机计算出“17”是 17,然后将其从列表中删除。我该怎么做呢?我还需要将“choicecrate”保留为整数。这可能是一个简单的问题,但我是初学者。

标签: python

解决方案


由于列表是按顺序排列的,一、二、三等。您可以通过将其与列表的长度进行比较来简单地检查用户输入的数字是否有效。

crates = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twentyone", "twentytwo", "twentythree", "twentyfour", "twentyfive", "twentysix"]

choicecrate = int(input("Which crate do you think is your lucky crate? "))

if 1 <= choicecrate <= len(crates):
    print("Input is in the list!")

推荐阅读