Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列表中的所有字符串转换为int_Python_List_Int - Fatal编程技术网

Python 如何将列表中的所有字符串转换为int

Python 如何将列表中的所有字符串转换为int,python,list,int,Python,List,Int,在Python中,我想将列表中的所有字符串转换为整数 我的任务是:我必须简单地对一些整数求和。 但是,我不能在以下代码中使用:for、while、sum、map、reduce、filter、import、eval、exec、compile、single 示例输入0: 1234 示例输出0: 十, 因此,如果我有: ls=['1','2','3'] 如何制作: ls=[1,2,3] def listSum(ls): def recursion(index, result):

在Python中,我想将列表中的所有字符串转换为整数

我的任务是:我必须简单地对一些整数求和。
但是,我不能在以下代码中使用:for、while、sum、map、reduce、filter、import、eval、exec、compile、single

示例输入0:

1234

示例输出0:

十,

因此,如果我有:

ls=['1','2','3']

如何制作:

ls=[1,2,3]

def listSum(ls):

    def recursion(index, result):
        if index == len(ls):
            return result
        return recursion(index + 1, result + ls[index])

    return recursion(0, 0)

ls = (input()).split()

ls = list(map(int, ls))
# print((ls))
print(listSum(ls))

正如您所尝试的,您可以递归地执行此操作:

def recursive_sum(lst):
    if not lst:
        return 0
    else:
        return int(lst[0]) + recursive_sum(lst[1:])

print(recursive_sum([1, 2, 3]))
# 6
如果要输入数字,只需执行以下操作:

print(recursive_sum(input().split()))

要将数字字符串列表转换为整数列表,可以使用如下递归函数:

def convert(ls):
    return ls and [int(ls[0]), *listSum(ls[1:])]

您可以使用递归获得问题的第一部分和第二部分:

b=['1', '2', '3', '4']
newarray=[] 
thesum=0
def recursion(hm): 
  global thesum, newarray
  if len(hm) == 0: 
     return thesum, newarray 
  thesum += int(hm[0])
  newarray.append(int(hm[0])) 
  return recursion(hm[1:]) 

recursion(b)  
# (10, [1, 2, 3, 4])

要将数字字符串列表转换为整数列表,而不使用问题中的任何关键字/名称黑名单,您还可以从列表中创建迭代器,并使用iter函数和回调函数,该函数返回迭代器中的下一项,转换为整数,直到迭代器耗尽:

ls = ['1', '2', '3']
i = iter(ls)
print(list(iter(lambda: int(next(i)), None)))
这将产生:

[1, 2, 3]

我不能在代码中使用以下内容:for、while、sum、map、reduce、filter、import、eval、exec、compile、single。将递归函数的return语句修改为:return recursionindex+1、result+intls[index]怎么样?但您的代码在使用递归时已经没有这些内容了。当然,您所需要做的就是在返回的和中添加int。当我运行代码时,我会键入带有空格的1234,然后创建一个列表['1'、'2'、'3'、'4']我不能简单地将建议副本中的所有答案串起来使用OP不允许使用的函数和结构。我必须输入这些数字。从字符串3 4 5转换为列表[3,4,5]并不是那么简单,你可以简单地调用。拆分如何简化它?简单是什么意思?如果你想简化它,你认为代码需要以什么方式进一步简化?