简体   繁体   English

将字符串列表转换为包含整数的元组列表

[英]Converting a list of strings, into a list of tuples containing integers

I'm parsing an XML file into a list of coordinates, and this is the line of code I'm using我正在将 XML 文件解析为坐标列表,这是我正在使用的代码行

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 that 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.其中 tree.getroot() 将 output 类似于 [" 100 200", " 40 90", ...] 我正在使用该代码去除空格,将其拆分为两个数字,并将它们转换为整数,但是我不禁查看该代码并认为它不能很快。 Any ideas on optimizing it a bit?关于优化它的任何想法?

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.就我而言,它采用 ['412.47298,198.204', 412.05498,198.597',...] 格式。 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]

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.也就是说,对于我能想到的大多数用例来说,这看起来已经足够好了。

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)]

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

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