Python - 直接扩展列表会导致无,为什么?

2023-09-27Python开发问题
7

本文介绍了Python - 直接扩展列表会导致无,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

x=[1,2,3]
x.extend('a')

输出:

x is [1,2,3,'a']

但是当我执行以下操作时:

But when I do the following:

[1,2,3].extend('a')

输出:

None

为什么 extend 对列表引用起作用,但对列表不起作用?

Why does extend work on a list reference, but not on a list?

我发现这个是因为我试图将 listB 附加到 listA,同时尝试将 listC 扩展到 listB.

I found this because I was trying to append a listB to a listA while trying to extend listC to listB.

listA.append([listB[15:18].extend(listC[3:12])])

假设列表不能直接附加/扩展.解决此问题的最流行的表单解决方法是什么?

Supposing lists cannot be directly appended / extending. What is the most popular work around form for resolving this issue?

推荐答案

list.extend 就地修改列表并且不返回任何内容,从而导致None.在第二种情况下,它是一个正在扩展的临时列表,在该行之后立即消失,而在第一种情况下,它可以通过 x 引用.

list.extend modifies the list in place and returns nothing, thus resulting in None. In the second case, it's a temporary list that is being extended which disappears immediately after that line, while in the first case it can be referenced via x.

在尝试将 listC 扩展到 listB 时将 listB 附加到 listA.

to append a listB to a listA while trying to extend listC to listB.

您可能想试试这个,而不是使用 extend:

Instead of using extend, you might want to try this:

listA.append(listB[15:18] + listC[3:12])

如果您想实际修改 listBlistC,则使用 extend 以多行简单的方式进行.

Or do it in multiple simple lines with extend if you want to actually modify listB or listC.

这篇关于Python - 直接扩展列表会导致无,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11