Lets say I have the following list:
StringLists = ['1,8,0,9','4,5,2,2','4,6,7,2','4,2,8,9']
And I want to generate the following result:
FinalList = [[1,8,0,9],[4,5,2,2],[4,6,7,2],[4,2,8,9]]
I am using the following code:
TempList = [d.split(',') for d in StringLists]
FinalList = list()
for alist in TempList:
FinalList.append([int(s) for s in alist])
The result is ok, but i was wondering if there is something more elegant. Any idea?
What about:
FinalList = [list(map(int, d.split(','))) for d in StringLists]
Note that if you are using Python 2, you do not have to cast the result:
FinalList = [map(int, d.split(',')) for d in StringLists]
One way to do it
>>> [[int(s) for s in string.split(',')] for string in StringLists]
[[1, 8, 0, 9], [4, 5, 2, 2], [4, 6, 7, 2], [4, 2, 8, 9]]
You can use:
StringLists = ['1,8,0,9','4,5,2,2','4,6,7,2','4,2,8,9']
print map(lambda s: map(int, s.split(',')), StringLists)
Output:
[[1, 8, 0, 9], [4, 5, 2, 2], [4, 6, 7, 2], [4, 2, 8, 9]]
这个怎么样:
TempList = [map(int, d.split(',')) for d in StringLists]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.