栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何遍历此n维数据集?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何遍历此n维数据集?

您可以使用

itertools.product
迭代某些值的笛卡尔乘积
1(在本例中为索引):

import itertoolsshape = [4,5,2,6]for idx in itertools.product(*[range(s) for s in shape]):    value = dataset[idx]    print(idx, value)    # i would be "idx[0]", j "idx[1]" and so on...

但是,如果要迭代的是一个numpy数组,则使用起来
更容易

np.ndenumerate

import numpy as nparr = np.random.random([4,5,2,6])for idx, value in np.ndenumerate(arr):    print(idx, value)    # i would be "idx[0]", j "idx[1]" and so on...

1您要求澄清

itertools.product(*[range(s) for s in shape])
实际操作。因此,我将对其进行详细说明。

例如,您有以下循环:

for i in range(10):    for j in range(8):        # do whatever

这也可以写成

product

for i, j in itertools.product(range(10), range(8)):#       ^^^^^^^^---- the inner for loop#       ^^^^^^^^^-------------- the outer for loop    # do whatever

这意味着

product
减少 独立 for循环的简便方法。

如果要将可变数量的

for
-loops转换为a
product
,则基本上需要两个步骤:

# Create the "values" each for-loop iterates overloopover = [range(s) for s in shape]# Unpack the list using "*" operator because "product" needs them as # different positional arguments:prod = itertools.product(*loopover)for idx in prod:     i_0, i_1, ..., i_n = idx   # index is a tuple that can be unpacked if you know the number of values.          # The "..." has to be replaced with the variables in real pre!     # do whatever

这等效于:

for i_1 in range(shape[0]):    for i_2 in range(shape[1]):        ... # more loops for i_n in range(shape[n]):  # n is the length of the "shape" object     # do whatever


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611637.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号