将项目附加到列表理解中的列表

发布于 2024-08-26 17:16:13 字数 537 浏览 7 评论 0原文

我有一个列表,例如 a = [[1,2],[3,4],[5,6]]

我想添加字符串 'a' 到列表中的每个项目a

当我使用:

a = [x.append('a') for x in a] 

它返回[None,None,None]

但如果我使用:

a1 = [x.append('a') for x in a]

那么它会做一些奇怪的事情。

a,但不是 a1[[1,2,'a'],[3,4,'a'],[5,6,' a']]

我不明白为什么第一个调用返回 [None, None, None] 也不明白为什么第二个调用在 a 而不是 a1 上发生变化。

I have a list, let's say, a = [[1,2],[3,4],[5,6]]

I want to add the string 'a' to each item in the list a.

When I use:

a = [x.append('a') for x in a] 

it returns [None,None,None].

But if I use:

a1 = [x.append('a') for x in a]

then it does something odd.

a, but not a1 is [[1,2,'a'],[3,4,'a'],[5,6,'a']].

I don't understand why the first call returns [None, None, None] nor why the second changes on a instead of a1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

独孤求败 2024-09-02 17:16:13

list.append 改变列表本身并返回 None。列表推导式用于存储结果,如果您只想更改原始列表,则在这种情况下这不是您想要的。

>>> x = [[1, 2], [3, 4], [5, 6]]
>>> for sublist in x:
...     sublist.append('a')
...
>>> x
[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]

list.append mutates the list itself and returns None. List comprehensions are for storing the result, which isn't what you want in this case if you want to just change the original lists.

>>> x = [[1, 2], [3, 4], [5, 6]]
>>> for sublist in x:
...     sublist.append('a')
...
>>> x
[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]
極樂鬼 2024-09-02 17:16:13

正如其他人所说,append 会改变列表本身,您不应该将其分配给变量。执行它会改变它的数据,有效地更新每个指向它的人。

但是,当我想以功能*的方式做一些事情,同时改变现有对象(而不是构造新对象,在本例中使用 a=[x + [' a'] 代表 a] 中的 x,或者特别是 x + ['a'])。

因此,如果您足够勇敢,您也可以这样做:

>>> a=[[1,2],[3,4],[5,6]]
>>> a=[x.append('a') or x for x in a]
>>> a
[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]

这是有效的,因为 append 返回 None,并且 or 继续搜索一个 true-y 值,x (它是一个列表,至少包含附加到其中的内容)。

为什么我需要这个?

假设您有一个列表,并且想要将其中的一些成员插入到新列表中,并相应地更新引用:

所以您拥有列表全部:

>>> all = [[], [], [], []]

其中一些被插入并更新到新列表 x

>>> x = [i.append('x') or i for i in all[:2]]
>>> x
[['x'], ['x']]

all 中的一些也被插入并更新到列表 y

>>> y = [i.append('y') or i for i in all[1:3]]

all 已更新:

>>> all
[['x'], ['x', 'y'], ['y'], []]

但是 x 也已更新:

>>> x
[['x'], ['x', 'y']]

并且 y 按预期生成:

>>> y
[['x', 'y'], ['y']]

总体而言,对于简单任务,我建议使用for 循环显式更新。这就是所谓的Pythonic。

从技术上讲,如果您有权访问列表类,则可以将其设为函数:

def more_functional_append(self, x):
    self.append(x)
    return self
  • 函数式编程基于每个语句本质上只做一件事,并且没有副作用(因此,不会变异和返回)。 append 不是很实用,因为它会改变列表(纯函数式编程只有不可变对象)并且不会返回结果以传递给其他操作(函数)。使用函数式编程概念,您可以创建无人能读懂的大行话,也称为“工作安全”或“糟糕的代码”。

As others have said, append mutates the list itself and you shouldn't assign it to a variable. Executing it changes it's data, effectively updating everyone pointing at it.

But, there's a trick I use when I want to do stuff in a functional* way while mutating existing objects (rather than constructing new ones, in this case using a=[x + ['a'] for x in a], or specifically the x + ['a']).

So, if you're brave enough you can also do this:

>>> a=[[1,2],[3,4],[5,6]]
>>> a=[x.append('a') or x for x in a]
>>> a
[[1, 2, 'a'], [3, 4, 'a'], [5, 6, 'a']]

This works because append returns None, and the or continues on to search for a truth-y value, which x is (it's a list with at least what was appended to it).

Why do I even need this?

Say you have a list and you want to insert some of it's members to a new list, and update the references accordingly:

So you have the list all:

>>> all = [[], [], [], []]

Some of it is inserted and updated to a new list x:

>>> x = [i.append('x') or i for i in all[:2]]
>>> x
[['x'], ['x']]

Some of all is also inserted and updated to a list y:

>>> y = [i.append('y') or i for i in all[1:3]]

all is updated:

>>> all
[['x'], ['x', 'y'], ['y'], []]

But x is also updated:

>>> x
[['x'], ['x', 'y']]

And y is generated as expected:

>>> y
[['x', 'y'], ['y']]

Overall, for simple tasks, I'd recommend using a for loop updating explicitly. This is what's considered pythonic.

Technically speaking, if you had access to the list class, you could make this a function:

def more_functional_append(self, x):
    self.append(x)
    return self
  • functional programming is based on every statement doing essentially one thing, and not having side effects (so, not mutating and returning). append is not very functional since it mutates a list (pure functional programming has only immutable objects) and does not return a result to pass to other actions (functions). Using functional programming concepts you can create great big one-liners no one can read, also known as "job security" or "bad code".
孤蝉 2024-09-02 17:16:13

对于第一种情况,它返回[None, None, None]的原因是因为list.append函数返回None,这就是它存储在列表中。

在第二种情况下,这是因为列表是可变的,每次追加值时,原始列表都会被修改。

您需要的是一个非就地追加运算符,例如 +。即[x + ['a'] for x in a]

For the first case, the reason it returns [None, None, None] is because the list.append function returns None, and that's what it stores in the list.

In the second case, it's because the list is mutable, and each time you append the value, the original list is modified.

What you need is a non-in-place append operator, such as +. i.e. [x + ['a'] for x in a].

难理解 2024-09-02 17:16:13

您可以在列表推导式中使用列表加法,如下所示:

a = [x + ['a'] for x in a] 

这给出了 a 所需的结果。在这种情况下,可以通过在循环之前将 ['a'] 分配给变量名来提高效率,但这取决于您想要做什么。

You can use list addition within a list comprehension, like the following:

a = [x + ['a'] for x in a] 

This gives the desired result for a. One could make it more efficient in this case by assigning ['a'] to a variable name before the loop, but it depends what you want to do.

记忆之渊 2024-09-02 17:16:13

(这是 Mike Graham 和 sykora 的答案的组合):

如果您只想就地更改值,请尝试常规的 for 循环,而不是列表理解:

for sublist in a:
    sublist.append('a')

如果您想单独保留 a ,然后将a1 中的结果:

a1 = [sublist + ['a'] for sublist in a]

正如他们所解释的,append 修改列表,但返回 None,而 + 单独保留列表,但返回一个新的附加列表。

(This is a combination of the answers by Mike Graham and sykora):

If you merely want to change the values in-place, try a regular for-loop, and not a list comprehension:

for sublist in a:
    sublist.append('a')

If you want to leave a alone, and put the result in a1:

a1 = [sublist + ['a'] for sublist in a]

As they explained, append modifies the list, but returns None, while + leaves the list alone, but returns a new, appended list.

过去的过去 2024-09-02 17:16:13

在列表理解的第一个值分配中,属性错误,“NoneType”对象没有属性“append”,有助于解释为什么您的列表 a 将加载 None。为了让我的控制台抛出错误,我使用 x 作为列表理解的变量以及迭代器。

Traceback (most recent call last):
x = [x.append('a') for x in a]
AttributeError: 'NoneType' object has no attribute 'append'

然后,我恢复到 for x 并抛出相同的错误。

Traceback (most recent call last):
a = [x.append('a') for x in a]
AttributeError: 'NoneType' object has no attribute 'append'

In the first value assignment of your list comprehension an Attribute Error, 'NoneType' object has no attribute 'append', helps explain why your list, a, will be loaded with None(s). To get my console to throw the error, I used x as a variable for the list comprehension and also as the iterator.

Traceback (most recent call last):
x = [x.append('a') for x in a]
AttributeError: 'NoneType' object has no attribute 'append'

Then, I reverted back to a for x and it threw the same error.

Traceback (most recent call last):
a = [x.append('a') for x in a]
AttributeError: 'NoneType' object has no attribute 'append'
晒暮凉 2024-09-02 17:16:13

保留 a = 并使用 a 的副作用:

[x.append('a') for x in a] 
print a

leave the a = and use the side effect on a:

[x.append('a') for x in a] 
print a
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文