[英]List of strings in ints ['123 121','42 23','23 23']
['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
With my list above I want to turn the elements into ints, I know that just using [int(x) for x in mylist]
will not work. ['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
我想将上面的列表元素转换为整数,我知道仅对[int(x) for x in mylist]
使用[int(x) for x in mylist]
行不通的。 So my question is how do you turn the list I have into a list of ints. 所以我的问题是如何将我拥有的清单转换为整数清单。
>>> L = ['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
>>> [int(y) for x in L for y in x.split()]
[136, 145, 136, 149, 137, 145, 138, 145, 139, 145, 142, 149, 142, 153, 145, 153]
Split the text first, then convert to int: 首先分割文本, 然后转换为int:
[map(int, elem.split()) for elem in originallist]
For Python 3, where map()
returns an generator, not a list, you can nest the list comprehension: 对于Python 3,其中map()
返回一个生成器,而不是一个列表,您可以嵌套列表理解:
[[int(n) for n in elem.split()] for elem in originallist]
which would work equally well under Python 2. 在Python 2下同样可以正常工作。
Quick demo: 快速演示:
>>> originallist = ['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
>>> [[int(n) for n in elem.split()] for elem in originallist]
[[136, 145], [136, 149], [137, 145], [138, 145], [139, 145], [142, 149], [142, 153], [145, 153]]
You can remove the nesting by moving the elem.split()
loop to the outer list comprehension, to the end: 您可以通过将elem.split()
循环移到外部列表理解末尾来删除嵌套:
[int(n) for elem in originallist for n in elem.split()]
which gives: 这使:
[136, 145, 136, 149, 137, 145, 138, 145, 139, 145, 142, 149, 142, 153, 145, 153]
As I tend to go to great lengths to avoid nested list comprehensions (I can never remember the order), I would do something like: 由于我会竭尽全力避免嵌套列表的理解(我永远不记得顺序),所以我会做类似的事情:
from itertools import chain
x = ['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
gen = chain.from_iterable(elem.split() for elem in x)
integers = [int(elem) for elem in gen]
You can try like this, 你可以这样尝试
>>> import re
>>> l=['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
>>> map(int, re.findall(r'\d+',' '.join(l)))
[136, 145, 136, 149, 137, 145, 138, 145, 139, 145, 142, 149, 142, 153, 145, 153]
>>> L = ['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
>>> map(int, ' '.join(L).split())
[136, 145, 136, 149, 137, 145, 138, 145, 139, 145, 142, 149, 142, 153, 145, 153]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.