将字符串列表转换为包含整数的元组列表 [英] Converting a list of strings, into a list of tuples containing integers

查看:54
本文介绍了将字符串列表转换为包含整数的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个 XML 文件解析为一个坐标列表,这是我正在使用的代码行

nodes = [(int(x.text.strip().split(' ')[0]),int(x.text.strip().split(' ')[1]))对于 tree.getroot()[0]] 中的 x

tree.getroot() 将输出类似 [" 100 200", " 40 90", ...]我正在使用该代码去除空格,将其拆分为两个数字,然后将它们转换为整数,但我不禁看着该代码并认为它​​不能很快.关于优化它的任何想法?

解决方案

不.但是可以简化很多.

<预><代码>>>>L = [' 1 2 ', '3 4 ']>>>[元组(int(y) for y in x.split()) for x in L][(1, 2), (3, 4)]

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

这篇关于将字符串列表转换为包含整数的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆