Re: How to get python to recognize each elemant as an integer?
|
Samson Reid |
|
3/25/2008 12:15:13 AM |
Code: ( python ) -
>>> num = ['1;3;2;3;2;1;4', '\n', '30;2;13;2;1;4;2', '2;3;2;1;4;2;4', '3;2;1;4;2;4;1', '2;1;4;2;4;1;4', '1;4;2;4;1;4;2'] -
>>> s = '\n'.join([str(result) for result in [sum([int(i) for i in item.split(';')]) for item in num if item != '\n']]) -
>>> s -
'16\n54\n18\n17\n18\n18' -
>>> print s -
16 -
54 -
18 -
17 -
18 -
18 -
>>>
Post Comments |
|
Samson, It works well, but i'm trying to keep a blank line if the '\n' was there to begin with, how can i tweak that so the solution would have been
'16\n\n54\n18\n17\n18\n18'
thanks
Post Comments |
|
Code: ( python ) -
results = [] -
for item in num: -
if item == '\n': -
results.append('') -
else: -
results.append(str(sum([int(i) for i in item.split(';')]))) -
print '\n'.join(results)
Code: ( text ) -
>>> 16 -
-
54 -
18 -
17 -
18 -
18 -
>>> print repr('\n'.join(results)) -
'16\n\n54\n18\n17\n18\n18' -
>>>
I got carried away with the list comprehension in my previous post. s could be: Code: ( python ) -
s = '\n'.join([str(sum([int(i) for i in item.split(';')])) for item in num if item != '\n'])
Post Comments |
|
Re: Thanks for breaking it up
|
Dolphi Powers |
|
3/25/2008 12:19:03 AM |
Hey Smasopn, Thanks for breaking it up onto many lines, i'm so fresh at this that when it's all squeezed into one line my mind breaks
Post Comments |
|