python - 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']
list above want turn elements ints, know using [int(x) x in mylist]
not work. question how turn list have list of ints.
split text first, then convert int:
[map(int, elem.split()) elem in originallist]
for python 3, map()
returns generator, not list, can nest list comprehension:
[[int(n) n in elem.split()] elem in originallist]
which work equally under python 2.
quick demo:
>>> originallist = ['136 145', '136 149', '137 145', '138 145', '139 145', '142 149', '142 153', '145 153'] >>> [[int(n) n in elem.split()] elem in originallist] [[136, 145], [136, 149], [137, 145], [138, 145], [139, 145], [142, 149], [142, 153], [145, 153]]
you can remove nesting moving elem.split()
loop outer list comprehension, end:
[int(n) elem in originallist n in elem.split()]
which gives:
[136, 145, 136, 149, 137, 145, 138, 145, 139, 145, 142, 149, 142, 153, 145, 153]
Comments
Post a Comment