开发者

How can i put number in the list in python [closed]

开发者 https://www.devze.com 2023-03-24 18:00 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_C百科 Closed 11 years ago.

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

精彩评论

暂无评论...
验证码 换一张
取 消