2017-02-08 31 views
-1

我需要从字符串类型转换为数字字符串转换为负数

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

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

我有一个问题转换负数时

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

ValueError: invalid literal for int() with base 10: '-5'

+0

据我所知,这段代码在python 3.5中工作得很好。 –

+0

'import re; list = map(lambda x:-int(re.search('[\ d] +',x).group()if' - 'in x else int(x),list)' –

回答

0

我不知道该怎么替换列表中的值,你将不得不为自己找出答案。此处的代码

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) 

可能工作。您的代码无法正常工作的原因是您将整个列表更改为字符串,而不是列表中的每个单独项目。知道这一点,如果你有更好的解决方案,试试它们。你上面写的

0

代码在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'] 
2

其实,我无法重现你的错误,它只是在Python 2.7.13

>>>int("-5") 
>>> -5 
工作

and python 3.4

因此,它可能是一个蟒蛇版本问题, 我建议通过重新安装更新,从site更新您的python版本,它会完全取代它(包未触动过),除非您使用,像anaconda这样的特殊分发..

处理您的列表(混合字符和数字)使用:

try: except: 声明。

0

请按照此示例。

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