【问题标题】:Comparing input integer to list将输入整数与列表进行比较
【发布时间】:2018-03-17 14:36:56
【问题描述】:
#Basically, for the input number given, return results that are smaller 
#than it compared with the list.

n = list(input('Please enter a Number:  '))
#map(int, str(n))
newlist = []
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

for n in a:
    if n > a:
        newlist.append(a)
        print(newlist)

不要求解决方案,而只是询问 n 如何作为列表工作,因为当我运行我的代码时,它说:

" if n > a:
TypeError: '>' not supported between instances of 'int' and 'list' "

【问题讨论】:

    标签: python python-3.x list input


    【解决方案1】:

    这是您需要的。您可以使用list comprehension 过滤a 以获取所需元素。

    x = int(input('Please enter a Number:  '))
    # Input 5 as an example
    
    a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    
    result = [i for i in a if i < x]
    
    print(result)
    # [1, 1, 2, 3]
    

    【讨论】:

    • 很好的解决方案,但问题是“不要求解决方案,只是询问 n 如何作为列表工作”。
    • @Tenflex,说实话我不理解用户的尝试。一方面,n 是来自字符串input 的列表。另一方面,for n in a 使用n 来迭代a 的元素。有时提供另一种方法可以启发 OP。
    • 是的,但问题并不清楚。但是在 sn-p n int 中使用变量的局部性比 n list 更局部
    【解决方案2】:

    假设您使用的是 python3,input() method 返回一个字符串。

    因此,如果您的用户输入值 42input() 将返回 "42",(type 'str')

    然后你将你的字符串转换成一个列表,所以继续第 42 个例子,你将拥有list("42") == ["4", "2"],并将这个列表存储在n 中。

    无论如何,您不再使用变量 n

    您编写的for 循环并不引用您之前创建的n 变量(请参阅namespaces),而是创建一个包含a 列表中每个数字的新变量。

    这意味着您将列表中的每个数字与整个列表进行比较:

    1 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    1 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    2 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    3 > [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    ...
    

    在 python3 中,这将引发 TypeError,而在 python2 中,行为将不是您所期望的。

    为了让您的代码正常工作,您可以获取用户输入并将其转换为整数,然后将该整数与列表中的每个数字进行比较,如果该数字小于输入整数,则将该数字附加到新列表中:

    myint = int(input('Please enter a Number:  '))
    # type(myint) == int
    newlist = []
    a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # for each (n)umber in list (a):
    for n in a:
        # if the provided number is higher than the actual number in list (a):
        if myint > n:
            newlist.append(n)
    # print the new list once its fully filled
    print(newlist)
    

    【讨论】:

    • 谢谢你。很好解释。很高兴我来到这个网站。
    • 如果您认为它回答了您的问题,请接受答案
    【解决方案3】:

    因为a 是一个列表,而您在迭代中的n 是列表a 内的一个整数值。例如在第零次迭代中 n = 1 但 a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 并说 n &gt; a 没有意义,不是吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多