I have numbers like this :
-1
1
2
3
-1
1
3
2
and i would like to put this number in list like [-1,1,2,3,-1,1,3,2]
and delete -1
from the list.
Like this?
>>> a = [-1, 1, 2, 3, -1, 1, 3, 2]
>>> a = [x for x in a if x != -1]
>>> a
[1, 2, 3, 1, 3, 2]
In [5]: l = [-1,1,2,3,-1,1,3,2]
In [6]: l = [item for item in l if item != -1]
In [7]: l
Out[7]: [1, 2, 3, 1, 3, 2]
here is the code:
In [1]: [int(x) for x in "-1 1 2 3 -1 1 3 2".split() if x!="-1"]
Out[1]: [1, 2, 3, 1, 3, 2]
Just a small improvement on agf's answer. You don't need to fiddle with indexing to remove newline characters. Rather use the strip method (it will also work for all kinds of line terminations, not just the Unix '\n'):
intlist = [int(x.strip()) for x in open(filename) if x.strip() != '-1']
精彩评论