【问题标题】:Python list reading integersPython列表读取整数
【发布时间】:2017-04-22 15:08:25
【问题描述】:

我正在尝试创建一个简单的脚本,该脚本应该计算列表中有多少 integersstrings。 起初列表是空的,然后要求用户用数字或字符串填充它,这是脚本:

lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters
while True:
   x = input("digit an int or string, 'stop' returns values: ")
   if(x=='stop'):
      False
      break

   i = lis.append(x)
   if isinstance(i, int): # check whether is integer
       num += 1
   else:
       lett += 1    

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

程序可以运行,但问题最终出现,因为当我打印列表时,它只看到字符串,例如,偶数返回为 '10'。

我需要解释器自动识别整数。

【问题讨论】:

  • 你需要使用x.isdigit(),因为x仍然是一个字符串isinstance()每次都会失败,因为它测试的是变量的数据类型而不是字符内容。但是除了这个之外,您的代码中还有很多,很多错误。我建议阅读 Python 教程以了解如何在其中编程。
  • The program works 我非常怀疑这一点。 lis.append(x) 返回 None。顺便说一句:False 之前的 break 什么都不做。
  • 致正在回答的用户:请停止回答此问题。它是广泛的,离题的,很可能不会帮助任何未来的用户。如果他阅读 Python 的初学者教程,它将使 OP 受益更多。在代码转储之后简单地发布代码转储对任何人都没有帮助。至少你可以为你的代码提供一个解释。
  • @mpf82 在他不会出错的意义上它会起作用。 lis.append(x) 返回 None 只是通过检查 i 是否属于 int 类型来复杂化问题——i 永远不会是 int,因为它是 None,因此他的代码称之为字符串。

标签: python string list integer


【解决方案1】:
lis = []            # list name

num, lett = 0, 0    # init counters of numbers and letters
while True:
  x = input("digit an int or string, 'stop' returns values: ")
  if(x=='stop'):
    break
  if x.isdigit():
    lis.append(int(x))
    num += 1
  elif x.isalpha(): 
    lis.append(x)
    lett += 1

print(lis)
print("there are " + str(num) + " numbers")
print("there are " + str(lett) + " strings")

结果

digit an int or string, 'stop' returns values:  1
digit an int or string, 'stop' returns values:  2
digit an int or string, 'stop' returns values:  3
digit an int or string, 'stop' returns values:  a
digit an int or string, 'stop' returns values:  b
digit an int or string, 'stop' returns values:  c
digit an int or string, 'stop' returns values:  stop
[1, 2, 3, 'a', 'b', 'c']
there are 3 numbers
there are 3 strings

【讨论】:

    【解决方案2】:

    您正在检查list.append 的返回值是否为整数,但不是。因此,它将它视为一个字符串。

    lis = []            # list name
    
    num, lett = 0, 0    # init counters of numbers and letters
    while True:
       x = input("digit an int or string, 'stop' returns values: ")
       lis.append(x)
       if(x=='stop'):
          break
    
    for items in lis:
        if items.isdigit(): # check whether is integer
            num += 1
        else:
            lett += 1   
    
    print(lis)
    print("there are " + str(num) + " numbers")
    print("there are " + str(lett) + " strings")
    

    【讨论】:

      【解决方案3】:
      d = l = 0
      res = []
      while True:
          s = input("input string or digit\n")
          if s == 'exit':
              break
      
          ## this is one way, might be faster to do it using isdigit suggested in the comment
          try:            
              temp = int(s)
              d += 1
          except ValueError:
              l += 1
          res.append(s)
      
      print(d)
      print(l)
      print(res)
      

      【讨论】:

      • 使用纯exception 子句被认为是不好的做法。请改用特定的例外。
      【解决方案4】:

      这是适用于我的 Python IDLE 版本 3.6.0 的解决方案(如果它不适合您,请回复):

      lis = []            # list name
      
      num, lett = 0, 0    # init counters of numbers and letters
      
      while True:
          try:
              x = input("digit an int or string, 'stop' returns values: ")
              i = lis.append(x)
              if(x=='stop'):
                  False
                  break   
          except ValueError:
              print("Not an integer!")
              continue
          else:
              num += 1
      
      print(lis)
      print("there are " + str(num) + " numbers")
      print("there are " + str(lett) + " strings")
      

      【讨论】:

      • 目前它不识别字符串,每个值都被视为整数,因为它只会增加num,即使我写'eggs'
      【解决方案5】:

      这是我的代码

      while True:
          l,num,lett = [],0,0
          while True:
              x = input('digit an int or string, "stop" returns values: ').lower().strip()
              try:
                  x = int(x)
              except:
                  pass
              if x == ('stop'):
                  break
              l.append(x)
      
          for element in l:
              if isinstance(element, int):
                  num += 1
              else:
                  lett += 1
      
          print (l)
          print ("there are " + str(num) + " numbers")
          print ("there are " + str(lett) + " strings")
          l,num,lett = [],0,0     #reset to go again
      

      【讨论】:

        【解决方案6】:

        您可以使用isdigit 并将您的代码更改为:

        lis = []            # list name
        
        num, lett = 0, 0    # init counters of numbers and letters
        while True:
            x = input("digit an int or string, 'stop' returns values: ")
            if(x=='stop'):
              False
              break
            if x.isdigit(): # check whether is integer
                lis.append(int(x))
                num += 1
            else:
                lis.append(x)
                lett += 1   
        
        print(lis)
        print("there are " + str(num) + " numbers")
        print("there are " + str(lett) + " strings")
        

        另外,你可以用这个来修复你的代码(它需要一个缩进并将它移动到你的主while):

        if isinstance(int(x), int): # check whether is integer
            num += 1
            lis.append(int(x))
        else:
            lett += 1
            lis.append(x)
        

        【讨论】:

        • 好的,它确实有效,谢谢。还有一个问题:当我打印列表时,我看到了这个输出 ['value1', 'value2', 'value3']。这意味着列表中充满了字符串,不是吗?如果 value1 是一个整数,输出是 [value1, 'value2', 'value3'] 还是不是?
        猜你喜欢
        • 1970-01-01
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 2019-07-30
        • 2018-05-07
        • 2010-12-26
        • 1970-01-01
        相关资源
        最近更新 更多