Python - 在 IF 中使用 AND 来引用 2 个变量

Python - using AND in an IF to reference 2 variables

我正在尝试使用模块 pyproj 编写一个 python 函数,它将根据两个因素进行坐标转换 - 文件名的结尾和 2 行的名称。

例如:if self.file_crs == 'IG' 如果文件结尾是 Irish Grid 的 IG

for idx,el in enumerate(row):
  if keys[idx].capitalize() in ['Easting', 'Northing']:

如果这两列分别称为 Easting 和 Northing

然后 运行

inProj = Proj(init='epsg:29903') # Irish Grid
outProj = Proj(init='epsg:4326') # WGS84
x1, y1 = row[1], row[2]  # easting, northing
x2, y2 = transform(inProj, outProj, x1, y1)
row[1], row[2] = y2, x2

我怎样才能把它们组合成这样:

if self.file_crs == 'IG' and keys[idx].capitalize() in ['Easting', 'Northing']:
  inProj = Proj(init='epsg:29903') # Irish Grid
  outProj = Proj(init='epsg:4326') # WGS84
  x1, y1 = row[1], row[2]  # easting, northing
  x2, y2 = transform(inProj, outProj, x1, y1)
  row[1], row[2] = y2, x2

我需要能够事先引用 idx 以便在我的 'if' 语句中识别它

编辑

键是正在解析的 csv 中的行名称。

if line_count == 0:
                    keys = row

行数如下

姓名 伊斯汀 北向 时间
测试 1 169973 77712 2020 年 1 月 1 日 09:51:03 上午

好的,我在临时测试工具中尝试了这个并且运行了:

class TestPositions:
    def __init__(self, crs):
        self.file_crs = crs

    def process_incoming_file(self, bucket, key, event):
        if self.file_crs == 'BNG':
            inProj = Proj(init="epsg:27700")  # British National Grid
            outProj = Proj(init="epsg:4326")  # WGS84
        else:
            inProj = Proj(init='epsg:29903')  # Irish Grid
            outProj = Proj(init='epsg:4326')  # WGS84

        try:

            decoded_content = ['Name|Easting|Northing|Time', 'Test1|169973|77712|01/01/2020 09:51:03 AM']
            print('processing data')
            rows = csv.reader(decoded_content, delimiter='|')
            for line_count, row in enumerate(rows):
                if line_count == 0:
                    keys = [title.lower() for title in row]
                    print('keys', keys)
                    isEasting = ('easting' in keys)
                else:
                    json_doc = {}
                    for idx, el in enumerate(row):
                        if keys[idx] in ['time', 'date serviced', 'timestamp']:
                            timestamp = self.format_timestring(el)
                        else:
                            json_doc[keys[idx]] = el

                    if isEasting:
                        json_doc['easting'], json_doc['northing'] = transform(inProj, outProj, json_doc['easting'], json_doc['northing'])
                        json_doc['latitude'] = json_doc.pop('easting')
                        json_doc['longitude'] = json_doc.pop('northing')
                    geom = Point(json_doc['Longitude'], json_doc['Latitude'])
                    WKB_format = wkb.dumps(geom, hex=True, srid=4326)

                    fid = uuid.uuid4()  # assign new UUID to each row

                    print(json_doc['name'])
                    print(fid)
                    print(timestamp)
                    print(WKB_format)
                    print(json_doc)

        except Exception as e:
            print(f'Exception: {e.__class__.__name__}({e})')

您可以看到我是如何在方法的开头生成 inProjoutProj 的,因此每次调用 process_incoming_file().

都会生成一次

我已经硬编码了 decoded_content。您需要您的原件:

            response = self.client.get_object(Bucket=bucket, Key=key)
            decoded_content = response['Body'].read().decode('utf-8')
            print(decoded_content)

            rows = csv.reader(decoded_content.splitlines(), delimiter=',')
            # no need to convert to a list

您会注意到我检查了第一行的列名并抛出异常,因为继续处理缺少的信息将毫无意义。

此外,一旦我将单元格复制到 json_doc,就不需要在循环中再次引用 row

更新:

我添加了对 'easting' 的检查作为将出现一组列名称的代理。因此,if isEasting: 进行转换,否则假定不需要转换。

回复以上回答

    def process_incoming_file(self, bucket, key, event):
        if self.file_crs == 'BNG':
            inProj = Proj(init="epsg:27700")  # British National Grid
            outProj = Proj(init="epsg:4326")  # WGS84
        else:
            inProj = Proj(init='epsg:29903')  # Irish Grid
            outProj = Proj(init='epsg:4326')  # WGS84

        try:
            response = self.client.get_object(Bucket=bucket, Key=key)
            decoded_content = response['Body'].read().decode('utf-8')
            print(decoded_content)
            print('processing data')
            rows = csv.reader(decoded_content.splitlines(), delimiter=',')
            for line_count, row in enumerate(rows):
                if line_count == 0:
                    keys = [title.lower() for title in row]
                    print('keys', keys)
                    isEasting = ('easting' in keys)
                else:
                    json_doc = {}
                    for idx, el in enumerate(row):
                        if keys[idx] in ['time', 'date serviced', 'timestamp']:
                            timestamp = self.format_timestring(el)
                        else:
                            json_doc[keys[idx]] = el

                    if isEasting:
                        json_doc['easting'], json_doc['northing'] = transform(inProj, outProj, json_doc['easting'], json_doc['northing'])
                        json_doc['latitude'] = json_doc.pop('easting')
                        json_doc['longitude'] = json_doc.pop('northing')
                    geom = Point(json_doc['longitude'], json_doc['latitude'])
                    WKB_format = wkb.dumps(geom, hex=True, srid=4326)

                    fid = uuid.uuid4()  # assign new UUID to each row

                    print(json_doc['name'])
                    print(fid)
                    print(timestamp)
                    print(WKB_format)
                    print(json_doc)

        except Exception as e:
            print(f'Exception: {e.__class__.__name__}({e})')