我是Python新手。所以我想在不使用发电机之类的花哨的东西的情况下完成循环。我有两个二维数组,一个是整数数组,另一个是字符串数组,如下所示:
整数2D列表:
这里,dataset2d[0][0]是表中的行数,dataset[0][1]是列数。所以下面的2D列表有6行4列
dataset2d = [
[6, 4],
[0, 0, 0, 1],
[1, 0, 2, 0],
[2, 2, 0, 1],
[1, 1, 1, 0],
[0, 0, 1, 1],
[1, 0, 2, 1]
]
字符串2D列表:
^{pr2}$partition[*][0]
即第一列是一个标签。对于A组,1、2和4是我需要从dataset2d中提取并应用公式的行号。所以这意味着我将读取1,转到dataset2d
中的第1行并读取第一列值,即dataset2d[1][0]
,然后从partition2d
读取2,转到数据集2d的第2行,读取第一列,即dataset2d[2][0]
。类似地,下一个我将读dataset2d[4][0]
。在
然后我将进行一些计算,获取一个值并将其存储在2D列表中,然后转到dataset2d中这些行的下一列。所以在这个例子中,下一列的值将是dataset2d[1][1]
,dataset2d[2][1]
,dataset2d[4][1]
。再次进行计算,得到该列的一个值,存储它。我将一直这样做直到到达dataset2d
的最后一列。在
partition2d
中的下一行是[B, 3, 5]
。所以我从dataset2d[3][0]
,dataset2d[5][0]
开始。获取该列的值作为公式。然后是实数dataset2d [3][1]
,dataset2d[5][1]
等,直到我到达最后一列。我一直这样做,直到分区2d中的所有行都被读取。
我尝试了:
for partitionRow in partition2d:
for partitionCol in partitionRow:
for colDataset in dataset2d:
print dataset2d[partitionCol][colDataset]
我面临的问题是:
更新1:
我从一个文本文件中读取内容,2D列表中的数据可能会有所不同,这取决于文件的内容和大小,但是file1(即dataset2d)和file2(即partition2d)的结构是相同的。在
更新2:因为Eric询问了输出应该是什么样子。在
0.842322 0.94322 0.34232 0.900009 (For A)
0.642322 0.44322 0.24232 0.800009 (For B)
这只是一个例子,数字是我随机输入的。 因此,第一个数字0.842322是将公式应用于dataset2d第0列的结果,即考虑了第1、2、4行的A组的dataset2d[partitioncol][0]。在
第二个数字0.94322是将公式应用于dataset2d第1列的结果,即组A的dataset2d[partitionCol][1],考虑了第1、2和4行。在
第三个数字0.34232是将公式应用于dataset2d的第2列的结果,即组A的dataset2d[partitionCol][2],考虑了第1、2和4行。同样,我们得到0.900009。在
第二行中的第一个数字,即0.642322,是将公式应用到dataset2d第0列(即dataset2d[partitioncol][0])的结果,该列考虑了第3、5行。等等。在
下面是一个使用迭代器的可扩展解决方案:
您可以使用Numpy(希望您不喜欢这样):
或者如果您不想安装Numpy,下面是您可以做的(实际上这是您想要的):
^{pr2}$两者都将打印:
第二个代码的说明(无数字):
这基本上是将每一行(
dataset2D[row_idx]
)作为一个列表整理在一起。所以这个表达式的结果是一个列表列表(来自指定的行索引)然后
zip(*rows)
将按列迭代(您想要的那个)。这是通过获取每行的第一个元素,然后将它们组合在一起形成一个tuple。在每次迭代中,结果存储在变量column
中。在那么在
for column in zip(*rows):
中,已经有了指定行中预期的按列迭代的元素!在要应用公式,只需将
print column,
改成你想做的事情。例如,我修改代码以包含行和列号:这将导致:
我希望这有帮助。在
要解决您的问题:
问题1可以使用切片来解决-如果您想在partition2d上从第二个元素迭代到某个东西
for partitionCol in partitionRow[1:]
。这将从第二个元素开始到最后对行进行切片。在比如说:
问题2我不明白你想要什么:)
相关问题 更多 >
编程相关推荐