python - 从 Python 中的数字列表创建包含五个元素的列表

标签 python list tuples

我正在使用 Python 3.7。

我有一个这样的数字元组:

 x = ((1,2,3,4,5,6,7,8,9....etc))

我想以迭代的方式获得一个除以 100 的列表列表,并从列表中获取五个数字......像这样:

[[[0.0], [0.01], [0.02], [0.03], [0.04]],
[[0.01], [0.02], [0.03], [0.04], [0.05]],
[[0.02], [0.03], [0.04], [0.05], [0.06]],
[[0.03], [0.04], [0.05], [0.06], [0.07]],
[[0.04], [0.05], [0.06], [0.07], [0.08]],
[[0.05], [0.06], [0.07], [0.08], [0.09]],... etc

我试过了,但它不能正常工作:

Data = [[[(interest_over_time_data+j)/100] for 
interest_over_time_data in range(5)]for j in 
interest_over_time_data]

实数不是连续数字的列表,所以我不能为每个元素添加 +1...

提前致谢!

最佳答案

  • 您想要一个列表的列表,这需要双重列表理解。
  • 您想要需要切片的滑动窗口,最好使用 itertools.islice

下面的这段代码创建了 5 个滑动子列表,每个子列表有 100 个分区。

import itertools

x = (1,2,3,4,5,6,7,8,9)
result = [[v/100.0 for v in itertools.islice(x,start,start+5)] for start in range(6)]

结果:

[[0.01, 0.02, 0.03, 0.04, 0.05], 
 [0.02, 0.03, 0.04, 0.05, 0.06], 
 [0.03, 0.04, 0.05, 0.06, 0.07], 
 [0.04, 0.05, 0.06, 0.07, 0.08], 
 [0.05, 0.06, 0.07, 0.08, 0.09],
 [0.06, 0.07, 0.08, 0.09]]

关于python - 从 Python 中的数字列表创建包含五个元素的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52662191/

相关文章:

java - 如何从 Java 发送一个 4 字节的 header 并在 Python 中读取它?

python - 我有 skimage 版本 0.12。我想专门下载0.14版本。我怎么做?

python - 如何在 python 中迭代条件检查?

python - 如何使用 Networkx 包以更好的分离度显示网络?

python - 添加数字,然后添加元组以作为元组列出,但它会删除外部元组

python - 元组列表 : remove tuples by comparison of element if they have another identical element

python - 如何将列表中的元素合并到 Python 3 中的另一个列表中?

python - 如何查找列表中元素的长度?

python - 从两个元组的元组创建列表

python - 元组列表(从元组中删除特殊项目)