簡體   English   中英

如何在不使用 Python 中的庫函數的情況下將“String”轉換為“Int”

[英]How to convert "String" to "Int" without using library functions in Python

我的作業需要它,我們有一位新老師說我們應該用谷歌搜索它,但我沒有找到有用的答案。

例如,我嘗試在沒有任何庫函數的情況下將 a = "546" 轉換為 a = 546。

我能想到的“最純粹”:

>>> a = "546"
>>> result = 0
>>> for digit in a:
        result *= 10
        for d in '0123456789':
            result += digit > d

>>> result
546

或者在允許的情況下使用@Ajax1234 的字典想法:

>>> a = "546"
>>> value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
>>> result = 0
>>> for digit in a:
        result = 10 * result + value[digit]

>>> result
546

您可以保留一個存儲數字鍵的字符串和整數值的字典,然后迭代該字符串。 在迭代字符串時,您可以使用enumerate來跟蹤索引,然后將 10 的冪減 1,然后乘以字典中的相應鍵:

a = "546"
length = 0
for i in a:
   length += 1
d = {'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
count = 0
counter = 0
for i in a:
   count += (10**(length-counter-1)*d[i])
   counter += 1
print(count)

輸出:

546

訣竅是546 = 500 + 40 + 6 ,或5*10^2 + 4*10^1 + 6*10^0

請注意指數如何只是索引(相反)。 使用它,您可以將這種方法推廣到一個函數中:

def strToInt(number):
    total = 0                             # this is where we accumulate the result
    pwr = len(number) - 1                 # start the exponent off as 2
    for digit in number:                  # digit is the str "5", "4", and "6"
        digitVal = ord(digit) - ord('0')  # using the ascii table, digitVal is the int value of 5,4, and 6.
        total += digitVal * (10 ** pwr)   # add 500, then 40, then 6
        pwr -= 1                          # make sure to drop the exponent down by one each time
    return total

你可以像這樣使用它:

>>> strToInt("546")
546
def stringToInt(s):
    result = 0
    value = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    for digit in s:
        result = 10 * result + value[digit]

    return result

您可以遍歷字符串並使用 ord 對每個字符執行操作。

例子:

a="546"
num=0
for i in a:
     num = num * 10 + ord(i) - ord('0')
astr = "1234"
num = 0
for index,val in enumerate(astr[::-1]):
    res = (ord(val) - ord('0')) * (10 ** index)
    num += (res)
def int(a):
ty = a.__class__.__name__
out = 0
di = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
      '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
if ty not in ("str", "int", "float", "bytes"):
    raise TypeError("unsupported format")
if a.__class__ == float:
    return a.__floor__()
elif a.__class__ == int:
    return a
else:
    ind = 0
    for val in a[::-1]:
        if val not in di:
            raise ValueError("invalid input")
        out += di[val]*(10**ind)
        ind += 1
        #print(out, di[val])
    return out
print(int("55"))
55

a=input() r=0 for i in a: r=r*10+(ord(i)-ord("0")) print(r) print(type(r))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM