简体   繁体   English

如何仅使用 car、cdr、cons 和其他函数拆分列表 (python)

[英]How to split a list only using car, cdr, cons and other functions (python)

we need to be able to make a function that has 1 list as an input.我们需要能够创建一个具有 1 个列表作为输入的函数。 We need to split the even numbers from the uneven numbers and put them in seperate lists.我们需要将偶数与奇数分开并将它们放在单独的列表中。 We are not permitted to make a second list and should be able to solve it only using recursion, and with car, cdr, cons, ... .我们不允许制作第二个列表,应该只能使用递归来解决它,并且使用 car, cdr, cons, ... 。

This is what I already have:这是我已经拥有的:

def split_list(list_a):
    if null(list_a):
        return []
    elif not even(car(list_a)):
        return cons(car(list_a), split_list(cdr(list_a)))
    else:
        return cons(splits_lijst(cdr(list_a)), car(list_a))
print(split_list([1, 2, 3, 4]))

I became the output: [1, 3, 4, 2]我变成了输出: [1, 3, 4, 2]

While it should be: [1, 3][2, 4]虽然它应该是: [1, 3][2, 4]

I really have no clue how to do this without making a secondary list.如果不制作辅助列表,我真的不知道如何做到这一点。

Just to be clear, the functions in the function 'split_list' are car, cdr, cons, null and even.需要明确的是,函数“split_list”中的函数是 car、cdr、cons、null 和 even。 Here you see the contents of those functions:在这里您可以看到这些函数的内容:

def car(a_list):
    return a_list[0]

def cdr(a_list):
    return a_list[1:]

def null(a_list):
    return True if len(a_list) == 0 else False

def cons(a, b):
    new_list = []
    if type(a) is list:
        for item in a:
            new_list.append(item)
    else:
        new_list.append(a)
    if type(b) is list:
        for item in b:
            new_list.append(item)
    else:
        new_list.append(b)
    return new_list

def even(x):
    if x == 1:
        return False
    elif x == 0:
        return True
    else:
        return even(x-2)

You need a way to make two lists during your iteration of one list.在迭代一个列表时,您需要一种方法来制作两个列表。 The best way to do that is to make a function that takes 3 arguments.最好的方法是创建一个接受 3 个参数的函数。 one for the input and 2 for the two output lists, often called accumulators.一个用于输入,两个用于两个输出列表,通常称为累加器。

The logic would be to return a list of the two accumulators when you have reached the end of the list.逻辑是当您到达列表末尾时返回两个累加器的列表。 If not you check the element for evenness and recurse by adding it to the even accumulator.如果不是,则检查元素的均匀性并通过将其添加到偶数累加器来递归。 If not you recurse by adding the element to the odd accumulator.如果不是,则通过将元素添加到奇数累加器来递归。

I think this would help you.我想这会对你有所帮助。

l=list(range(10))
evens=[]
odds=[]
for x in l:
    if x%2==0:
        evens.append(x)
    else:
        odds.append(x)
print(evens,odds)

the below one will use only one additional list,(in case you don't require the original one):下面的将仅使用一个附加列表,(以防您不需要原始列表):

l=list(range(10))
odds=[]
for x in l:
    if x%2==0:
        continue
    else:
        l.remove(x)
        odds.append(x)
print(l,odds)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM