python - 如何在列表理解中执行作业?

标签 python list-comprehension

所以在Python 3.6中为tress创建测试用例时,我想知道是否有一个好的方法来执行列表推导中的赋值等操作。我应该使用 lambda 吗?

我要插入

Prev_Node.next = Node(i)
Prev_Node = Node(i)

进入

iList = [1,2,3,4,10]
Prev_Node = Node(iList[0])
l1 = [Node(i) <Any assignment action?> for i in iList[1:])]

提前感谢您的宝贵时间,

最佳答案

使用迭代器遍历你的列表,不要摆弄 .Next 等来构建你自己的。

如果你正在寻找列表的头部和尾部,那么你可以这样做:

int_list = [1, 2, 3, 4, 10]
node_list = [Node(i) for i in int_list]
head = node_list[0]  # Get the head Node and leave it in the list.
head, *tail = node_list  # Get the head Node and remove it from the list.

并像这样迭代

for node in node_list:
    print(node)

看看各种list function关于如何进一步操作现有列表。

关于python - 如何在列表理解中执行作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55644061/

相关文章:

python - 滑动窗口操作的 Numpy 向量化

python - 生成器表达式和。列表推导

python - 在 Python 中将列表的列表转换为元组

python - 当列表值为字符串时,如何将 else 与列表理解一起使用?

分析日志文件的Python脚本

python - ctypes 为 c_ulong 重新实现 rshift

python - 如何将下面的代码转换为一行接受输入?

python - 如何使用另一个列表通过列表理解对列表进行子集化

python - 在同一个 Django 管理页面中添加外键相关实体

Python - 使用内置函数与数学模块进行数学运算