python中的LISP缺点 [英] LISP cons in python

查看:112
本文介绍了python中的LISP缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中是否有cons的等效项? (高于2.5的任何版本)

Is there an equivalent of cons in Python? (any version above 2.5)

如果是,它是内置的吗?还是我需要easy_install获得一个模块?

If so, is it built in? Or do I need easy_install do get a module?

推荐答案

在Python中,使用基于数组的list类比使用Lisp样式的链表更为典型.但是在它们之间进行转换并不难:

In Python, it's more typical to use the array-based list class than Lisp-style linked lists. But it's not too hard to convert between them:

def cons(seq):
    result = None
    for item in reversed(seq):
        result = (item, result)
    return result

def iter_cons(seq):
    while seq is not None:
        car, cdr = seq
        yield car
        seq = cdr

>>> cons([1, 2, 3, 4, 5, 6])
(1, (2, (3, (4, (5, (6, None))))))
>>> iter_cons(_)
<generator object uncons at 0x00000000024D7090>
>>> list(_)
[1, 2, 3, 4, 5, 6]

这篇关于python中的LISP缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆