-2

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.

agf
  • 171,228
  • 44
  • 289
  • 238
graph
  • 389
  • 2
  • 5
  • 10
  • Where do you get these numbers from? Keyboard input, a file, ...? – Brian Neal Aug 03 '11 at 13:09
  • possible duplicate of [Remove all occurences of a value from a Python list](http://stackoverflow.com/questions/1157106/remove-all-occurences-of-a-value-from-a-python-list) – Jacob Aug 03 '11 at 13:09
  • 1
    Why are you putting -1 if you are going to delete it? – Fábio Diniz Aug 03 '11 at 13:13
  • The question lacks some "context". Please be more specific about what you want. Is that a generic routine you want to write ? Do you need to remove only "-1" occurences from any given list ? – Raphael Jolivet Aug 03 '11 at 13:13
  • I am get this numbers form this code: x = [5,6,7,8,9,10,11,12,13] y = [5,6,7,8,9,10,11,12,13] for i in x: for j in y: x, elist = gt.shortest_path(g, g.vertex(i), g.vertex(j)) xx = [str(v) for v in x] print xx print len(xx)-1 . So the number in the form of a column, and i want her in the form of a list without -1. – graph Aug 03 '11 at 20:49

4 Answers4

1

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]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1
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]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

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]
HYRY
  • 94,853
  • 25
  • 187
  • 187
0

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']