['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153']
通过上面的列表,我想将元素转换为整数,我知道仅使用是[int(x) for x in mylist]
行不通的。所以我的问题是如何将我拥有的列表变成整数列表。
问问题
87 次
5 回答
3
>>> 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]
于 2013-04-05T11:39:23.350 回答
2
先拆分文本,然后转换为 int:
[map(int, elem.split()) for elem in originallist]
对于 Python 3,其中map()
返回的是生成器,而不是列表,您可以嵌套列表推导:
[[int(n) for n in elem.split()] for elem in originallist]
这在 Python 2 下同样有效。
快速演示:
>>> 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]]
elem.split()
您可以通过将循环移动到外部列表理解来删除嵌套:
[int(n) for elem in originallist for n in elem.split()]
这使:
[136, 145, 136, 149, 137, 145, 138, 145, 139, 145, 142, 149, 142, 153, 145, 153]
于 2013-04-05T11:38:58.327 回答
1
由于我倾向于竭尽全力避免嵌套列表推导(我永远记不起顺序),因此我会执行以下操作:
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]
于 2013-04-05T11:42:03.733 回答
1
你可以这样试试
>>> 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]
于 2013-04-05T11:46:58.077 回答
0
>>> 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]
于 2013-04-05T11:47:28.230 回答