[英]How to loop through a nested loop and enumerate
I am having a problem with my nested loops.我的嵌套循环有问题。 I am getting an output, but it is duplicating each output for the number of fields in my data set.
我得到了一个输出,但它正在为我的数据集中的字段数复制每个输出。
for dat in data_body:
x = float(dat[5])
y = float(dat[6])
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(x,y)
feature.SetGeometry(point)
for i, d in enumerate(dat):
for j, field in enumerate(new_fields):
if i == j:
feature.SetField(field, d)
layer.CreateFeature(feature)
For my datasets, the list of lists data_body
has 13 rows of data and 55 columns (ie 55 positions).对于我的数据集,列表
data_body
有 13 行数据和 55 列(即 55 个位置)。 For my list new_fields
I have a 55 values, which correspond to the columns of data_body
list of lists.对于我的列表
new_fields
我有 55 个值,它们对应于列表的data_body
列表的列。 Thus, in my code block for the object feature.SetField(field, d)
.因此,在我的对象
feature.SetField(field, d)
代码块中。 I should have each value of the data_body correspond to each unique field, as long as rows match each other, ie i
and j
.我应该让 data_body 的每个值对应于每个唯一的字段,只要行彼此匹配,即
i
和j
。 However, rather getting an object back with 13 rows of data corresponding with column values corresponding to the values in new_fields
.但是,而是取回一个对象,其中包含与
new_fields
值对应的列值对应的 13 行数据。 I get 13 * 55 values, ie 715 rows, where values are missing for ~ 50% of the data.我得到 13 * 55 个值,即 715 行,其中大约 50% 的数据缺少值。 My output data table kind of looks like a triangle of data.
我的输出数据表看起来像一个三角形的数据。
I am not sure if my question makes sense, but if it does, any help with my nested looping strategies would be helpful.我不确定我的问题是否有道理,但如果有道理,对我的嵌套循环策略的任何帮助都会有所帮助。 i think my issue is my conceptualization of what my loop is actually doing, as well as what my
if
statement might be doing.我认为我的问题是我对循环实际在做什么的概念化,以及我的
if
语句可能在做什么。
As avasal said, you want to iterate over dat and new_fields at the same time, and the easiest way to do this is to use zip
:正如 avasal 所说,你想同时迭代 dat 和 new_fields,最简单的方法是使用
zip
:
for d, field in zip(dat, new_fields):
feature.SetField(field, d)
layer.CreateFeature(feature)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.