在没有for循环的情况下对列表的每个元素进行操作

2024-04-28 12:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我知道这个问题听起来很奇怪,但我发现自己的处境可能需要避免在列表上循环,除非我设法找出问题的根源

问题是:

def SomeFunction(args):
    someList = [here, are, list, elements]
    print (someList) # works normal
    for elem in someList:
        print (elem) # side effects observed here (and not sure why at this stage), only the first element is printed

有没有其他方法可以像for循环那样访问列表元素


Tags: 列表forheredefargselementsarelist
3条回答

通常,这可以使用递归实现

下面是我使用递归处理列表的算法:-

函数进程\列表(将列表的第一个元素作为参数)

  1. 如果列表已结束: 返回(结束函数执行)

  2. 处理当前元素

  3. 调用函数process_list(将其传递给列表中的下一个元素)

您可以使用while循环迭代列表:

i = 0
sizeofList = len(wordList) 
while i < sizeofList :
    print(wordList[i]) 
    i += 1

可以使用递归或切片

def print_ele(elements):
    if(len(elements)>0):
        print(elements[0])
        print_ele(elements[1:])

//Or 
elements[0:2]

相关问题 更多 >