简体   繁体   English

实现这4条线的最Pythonic方式?

[英]most Pythonic way of achieveing these 4 lines?

I have a csv cell value, row[13] that contains the following text: POINT (174.29635 -41.60557) 我有一个csv单元格值, row[13]包含以下文本: POINT (174.29635 -41.60557)

I need to strip out the text and brackets, and convert the two numbers to float, each assigned to a var:- 我需要去掉文本和方括号,并将两个数字转换为浮点数,每个数字都分配给一个var:

geo_pair = row[13].replace("POINT (", "")
geo_pair = geo_pair.replace(")", "")
self.longitude, self.latitude = geo_pair.split(" ")
self.longitude, self.latitude = float(self.longitude), float(self.latitude)

I'm pretty sure there is a cleaner way of doing this, and I wondered what someone who knows what they are doing would do! 我很确定有一种更干净的方法可以做到,而且我想知道知道自己在做什么的人会做什么!

Since the format is fixed and consists of prefix, data, and suffix, I would use slicing to remove prefix and suffix: map(float, s[7:-1].split()) . 由于格式是固定的,并且由前缀,数据和后缀组成,因此我将使用切片来删除前缀和后缀: map(float, s[7:-1].split())

This is clear and simple at the same time: 同时这既清楚又简单:

>>> s = "POINT (174.29635 -41.60557)"
>>> longitude, latitude = map(float, s[7:-1].split())

This also works upon sign changes or when the number of decimal places changes. 这也适用于符号更改或小数位数更改时的情况。

And by the way, as long as you are not parsing tons of input, it does not really matter which way to chose. 顺便说一句,只要您不解析大量输入,选择哪种方式就没有关系。 It's mostly a matter of taste and most likely not performance-critical in your case. 这主要是一个品味问题,对于您的情况而言,很可能不是关键性能。 So don't spend too much time with this :-). 因此,不要在此上花太多时间:-)。

Use the regex? 使用正则表达式?

>>> map(float, re.search(r'\((.*)\)', s).group(1).split())
[174.29635, -41.60557]
>>> 

How about this? 这个怎么样?

>>> a, b = map(float, row.translate(None, "POINT()").split())
>>> a
174.29635
>>> b
-41.60557

where 哪里

row = "POINT (174.29635 -41.60557)"

I use split(sep1, 1)[-1].split(sep2, 1)[0] : 我使用split(sep1, 1)[-1].split(sep2, 1)[0]

geo_pair = row[13].split("POINT (", 1)[-1].split(")", 1)[0]
self.longitude, self.latitude = map(float, geo_pair.split())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM