简体   繁体   English

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

[英]How do I perform assignments in list comprehension?

So while creating test cases for tress in Python 3.6, I was wondering if there is a good way to perform actions such as assignment in the list comprehension.因此,在 Python 3.6 中为 tress 创建测试用例时,我想知道是否有一种很好的方法来执行列表理解中的赋值等操作。 Should I use lambda?我应该使用 lambda 吗?

I want to insert我想插入

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

into进入

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

Thank you for your time in advance,提前感谢您的时间,

Use iterators to traverse your list, don't fiddle around with .Next etc to build your own.使用迭代器遍历您的列表,不要摆弄.Next等来构建您自己的列表。

If you're looking for list head and tail, then you could do something like:如果您正在寻找列表头和尾,那么您可以执行以下操作:

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.

and iterate like并像这样迭代

for node in node_list:
    print(node)

Take a look at the various list function on how to further manipulate an existing list.查看有关如何进一步操作现有列表的各种列表功能

You can't do assignments within a list comprehension.你不能在列表理解中做作业。 Trying to do so raises a `SyntaxError, eg:尝试这样做会引发`SyntaxError,例如:

[x = 0 for _ in range(1)]
# SyntaxError: invalid syntax

I suppose an awful hack to try to achieve this could be to define a function which you call in the list comprehension which does the assignment (using global variables).我想尝试实现这一点的一个可怕的技巧可能是定义一个函数,您可以在列表理解中调用该函数来进行赋值(使用全局变量)。 But this would be much worse than just using a normal for loop instead of a list comprehension.但这比使用普通的 for 循环而不是列表理解要糟糕得多。 Basically, any time that using a list comprehension doesn't work right away, you're probably better off with a for loop.基本上,任何时候使用列表推导式无法立即工作,您可能最好使用 for 循环。 It'll be easier for you to program and for others to understand.你会更容易编程,也更容易让其他人理解。

# hacky; don't do this
def set_x(val):
    global x
    x = val

[set_x(i) for i in range(3)]
x # 2

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

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