簡體   English   中英

將字符串轉換為負數

[英]Convert string to negative number

我需要從字符串類型轉換為數字

list = ["-5","4","-3","variable"]  # Input

list = [-5,4,-3,"variable"]        # epected output

我在轉換負數時遇到問題

list[0]=int(list[0])

ValueError:int() 的無效文字,基數為 10:'-5'

實際上,我無法重現您的錯誤,它僅適用於 python 2.7.13

>>>int("-5")
>>> -5

並在python 3.4中

所以,這可能是 python 版本問題,我建議更新你的 python 版本,通過從站點重新安裝較新的版本,它將完美地替換它(包未受影響),除非你使用的是像 anaconda 這樣的特殊發行版..

處理您的列表(混合字符和數字)使用:

try: except:聲明。

我在matplotlib xticklabels Text 屬性中遇到了這個問題。 負數的減號被編碼為“減號”:

[-] 是一個減號(Unicode 2212)。

減號:[&minus]; 又名 [&#8722]; 又名 [&#x2212];

https://en.wikipedia.org/wiki/Wikipedia:Hyphens_and_dashes

Python 似乎將減號編碼為“連字符減號”,Unicode 002D:

[-] 是連字符減號(ASCII 鍵盤,Unicode 002D)

連字符減號:[&#45]; 又名 [&#x002D];

下面是一個例子:

>> import matplotlib.pyplot as plt
>> import re
>> x = [0,1,2,3,4,5]
>> y = [0,1,2,1,2,1]

>> fig,ax = plt.subplots(1)
>> plt.plot(x,y)

玩具數據的散點圖 .

如果我們嘗試獲取 xticklabels,如果我們想手動編輯它們,我們使用:

>> l = ax.get_xticklabels()
>> ticks = [i.get_text() for i in l]
>> print(ticks)

['−1', '0', '1', '2', '3', '4', '5', '6']

>> ord(ticks[0])

8722

嘗試將其轉換為整數:

>> l = ax.get_xticklabels()
>> ticks = [int(i.get_text()) for i in l]

ValueError: invalid literal for int() with base 10: '−1'

這與問題中的錯誤相同,其他人很難重現。 要修復它,請使用正則表達式:

ticks = [int(re.sub(u"\u2212", "-", i.get_text())) for i in l]
print(ticks)
print(ticks[0] - 1)

[-1, 0, 1, 2, 3, 4, 5, 6]
-2

>> ord(ticks[0])

45

我不知道如何替換列表中的值,您必須自己找出來。 這段代碼在這里

abc = "abcdefghijklmnopqrstuvwxyz" #to make sure there are no letters in the string
list = ["-5","4","-3","variable"]
def MightWork(list):
    newlist = []
    for item in list:
        if set(abc) & set(list[item]) = False:
            newlist.append(int(list[item]))
return newlist

list = MightWork(list)

可能工作。 您的代碼不起作用的原因是因為您將整個列表更改為字符串,而不是列表中的每個單獨項目。 知道了這一點,如果您有更好的解決方案,請嘗試它們。

你上面寫的代碼在python3中運行良好

list1 = ["-5","4","-3","variable"]
list2 = []
print(list1)
for item in list1:
    try:
        list2.append(int(item))
    except ValueError as e:
        list2.append(item)
print(list2)

輸出

['-5', '4', '-3', 'variable']
[-5, 4, -3, 'variable']

按照這個例子。

list=[-1,2,'car']
convert=[]
for i in list.split():
    if type(i) == str:
        try:
            convert.append(type(map(int,i)))
        except ValueError:
            convert.append(type(i))
    return convert

暫無
暫無

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

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