簡體   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