开发者

Converting a list of strings, into a list of tuples containing integers

开发者 https://www.devze.com 2023-03-17 06:36 出处:网络
I\'m parsing an XML file into a list of coordinates, and this is the line of code I\'m using nodes = [(int(x.text.strip().split(\' \')[0]),int(x.text.strip().split(\' \')[1])) for x in tree.getroot()

I'm parsing an XML file into a list of coordinates, and this is the line of code I'm using

nodes = [(int(x.text.strip().split(' ')[0]),int(x.text.strip().split(' ')[1])) for x in tree.getroot()[0]]

Where tree.getroot() will output something like [" 100 200", " 40 90", ...] I'm using t开发者_StackOverflow社区hat code to strip the whitespace, split it into the two numbers, and convert them to integers, but I can't help looking at that code and thinking it just can't be very fast. Any ideas on optimizing it a bit?


Nope. But it can be simplified a lot.

>>> L = [' 1 2 ', '3 4 ']
>>> [tuple(int(y) for y in x.split()) for x in L]
[(1, 2), (3, 4)]


You should always ask yourself why you do want to optimize something. It doesn't really matter if you think something is fast and sometimes it doesn't even matter if it is fast as long as it is fast enough.

That said, this looks good enough for most use cases I can think of.


Just wanted to thank the Ignacio. Needed similar approach to translate coordinates into list of tuples. In my case it was in ['412.47298,198.204', 412.05498,198.597',...] format. Have to get rid of comma and convert it into float format.

That worked by

some_float = ['412.47298,198.204', '412.05498,198.597'] 
[tuple(float(y) for y in x.split(",")) for x in some_float]
0

精彩评论

暂无评论...
验证码 换一张
取 消