繁体   English   中英

Python列表读取整数

[英]Python list reading integers

我正在尝试创建一个简单的脚本,该脚本应该计算列表中有多少个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”。

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

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)

您正在检查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")

这是适用于我的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")

这是我的代码

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

您可以使用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)
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM