使用多个范围语句的 Python 列表初始化

2023-11-08Python开发问题
10

本文介绍了使用多个范围语句的 Python 列表初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想要一个长列表,例如 [1,2,3,4,5,15,16,17,18,19].为了初始化它,我尝试输入:

I want one long list, say [1,2,3,4,5,15,16,17,18,19] as an example. To initialize this, I try typing:

new_list = [range(1,6),range(15,20)]

但是这并没有做我想要的,返回:

However this doesn't do what I want, returning:

[[1, 2, 3, 4, 5], [15, 16, 17, 18, 19]]

当我这样做时:

len(new_list)

它返回 2,而不是我想要的 10 个元素(因为它在列表中创建了 2 个列表).显然,在这个例子中,我可以只输入我想要的内容,但我正在尝试对一些奇怪的迭代列表执行此操作,例如:

It returns 2, instead of the 10 elements I wanted (since it made 2 lists inside the list). Obviously in this example I could just type out what I want, but I'm trying to do this for some odd iterated lists that go like:

new_list = [range(101,6284),8001,8003,8010,range(10000,12322)]

需要一维列表而不是列表列表(或任何最好的名称).我猜这真的很容易而且我很想念它,但是经过相当多的搜索后,我没有想出任何有用的东西.有什么想法吗?

Desiring a 1-D list instead of a list of lists (or whatever it's best called). I'm guessing this is really easy and I'm missing it, but after quite a bit of searching I've come up with nothing too useful. Any ideas?

推荐答案

在 Python 2.x 上试试这个:

Try this for Python 2.x:

 range(1,6) + range(15,20)

或者如果你使用的是 Python3.x,试试这个:

Or if you're using Python3.x, try this:

list(range(1,6)) + list(range(15,20))

用于处理中间元素,对于 Python 2.x:

For dealing with elements in-between, for Python 2.x:

range(101,6284) + [8001,8003,8010] + range(10000,12322)

最后是处理中间元素,对于 Python 3.x:

And finally for dealing with elements in-between, for Python 3.x:

list(range(101,6284)) + [8001,8003,8010] + list(range(10000,12322))

这里要记住的关键方面是,在 Python 2.x 中 range 返回一个列表,而在 Python 3.x 中它返回一个可迭代对象(因此需要将其显式转换为列表).对于将列表附加在一起,您可以使用 + 运算符.

The key aspects to remember here is that in Python 2.x range returns a list and in Python 3.x it returns an iterable (so it needs to be explicitly converted to a list). And that for appending together lists, you can use the + operator.

这篇关于使用多个范围语句的 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