Python:检测列表中的非特定输入

Python: Detecting non-specific inputs in lists

我的列表是通过选择附加的。基本上,我问一个问题,无论你输入什么,都会进入这个列表。

我也问你输入多少。这会创建重复项,因此如果您输入的数量大于 1,我会使用连接来添加增量数字。 (例如,

"What would you like to add to the list?" 用户:"dog" "How many?" 用户:“3”

列表 = 狗、狗 2、狗 3、猫)

对于我的特定程序,我无法知道用户可能会输入什么,所以我不能使用 if ____ in _____ 可以吗?另外,现在我有这些连接的字符串,名为 'dog' 和一个数字。我只想让代码在列表中检测狗,但同样,我不知道狗是否在列表中!可以是任何东西!

尝试使用 Set 和 list 之间的转换。添加新输入时,将列表转换为 Set 以避免重复元素;当您想使用某些列表属性时,将其转换为列表。

对于您描述的问题,使用字典比使用列表更有用。可以这样实现

my_dict = {}
my_dict['dog'] = 3

将 what-ever-thing 添加为字典的键,将 how many 添加为它的值。

如果您试图找出用户为 'how many' 输入的整数值,您可以通过多种方式来完成此操作。 一种是拥有一本包含数据的字典。 例如,

>>> dict = {} 
>>> "What would you like to add to the list?" User: "dog" "How many?" User: "3"
>>> dict["dog"] = 3
>>> dict
dict = {'dog': 3}
>>> dict['cat'] = 2
dict = {'dog': 3, 'cat': 2}
>>> for key in dict:
>>>    print(key + ": " + str(dict[key]))
dog: 3
cat: 2

通过这种方式,您可以遍历字典中的不同键,并能够知道每个键的 'how many'。

字典中的每一项现在都对应于它的数值。

根据描述和评论,这是您需要的示例代码,我正在创建一个字典,并将项目存储为键,将计数存储为值。

item = input("What would you like to add to the list?") # User Input : Dog
cnt = int(input("How many?")) : User Input : 3

d = {item:cnt} # dict created {'dog': '3'}

def callFunctionNtimes(d, key):
    """
    Function which check the key (dog) is present in the dict, if it is present call callYourFunction as many times as it is the value(count) of the key.
    """
    cnt = d.get(key, 0)
    for c in range(0, cnt):
        callYourFunction()