2009-09-25 65 views
2

什麼是字符串轉換的格式"1-2-3-4"到列表[1, 2, 3, 4]最好的方法是什麼?該字符串也可能爲空,在這種情況下,轉換應返回空列表[]的Python: 「1-2-3-4」[1,2,3,4]

這是我有:

map(lambda x: int(x), 
    filter(lambda x: x != '', 
      "1-2-3-4".split('-'))) 

編輯:對不起那些之前我糾正我的問題誰回答的,目前還不清楚第一分鐘左右。

+0

你實現你沒有檢查空字符串,對吧?你正在檢查新列表的項目是否爲空字符串。這些是不同的事情。 – SilentGhost 2009-09-25 18:48:52

+0

@SilentGhost:我不知道,我的算法可以製成不同的,但我的方法效果爲好。 '「」.split(「 - 」)'返回'[「」]''。我的算法的漸近時間複雜度比理想情況差,但在這種情況下它可以忽略不計。 – 2009-09-26 14:27:43

回答

12

您可以使用列表理解來縮短它。使用if來說明空字符串。

the_string = '1-2-3-4' 

[int(x) for x in the_string.split('-') if x != ''] 
+0

你爲什麼要檢查這樣的空字符串? – SilentGhost 2009-09-25 18:44:41

+0

SilentGhost,問題說在空字符串的情況下它應該返回一個空列表:「字符串也可能是空的,在這種情況下,轉換應該返回一個空列表[]。」 – 2009-09-25 18:51:32

+0

那你爲什麼要這樣做呢?你不知道什麼對象評價爲False? – SilentGhost 2009-09-25 18:54:42

8
>>> for s in ["", "0", "-0-0", "1-2-3-4"]: 
...  print(map(int, filter(None, s.split('-')))) 
... 
[] 
[0] 
[0, 0] 
[1, 2, 3, 4] 
+0

對不起,我現在糾正了我的問題。 – 2009-09-25 18:34:51

+0

@blahblah,我更新我的回答太 – 2009-09-25 18:36:35

+0

這不會ADRESS空刺痛情況。 – voyager 2009-09-25 18:44:11

4

轉換的高階函數以一個更可讀的列表理解

[ int(n) for n in "1-2-3-4".split('-') if n != '' ] 

其餘部分是細。

2

從你的例子的格式,你要廉政局在列表中。如果是這樣,那麼你將需要將字符串數字轉換爲int。如果不是,那麼在字符串拆分後完成。

text="1-2-3-4" 

numlist=[int(ith) for ith in text.split('-')] 
print numlist 
[1, 2, 3, 4] 

textlist=text.split('-') 
print textlist 
['1', '2', '3', '4'] 

編輯:修改我的答案以反映問題中的更新。

如果列表可以那麼畸形,如果你的朋友「的try ... catch」。這將強制該列表格式正確,或者您得到一個空列表。

>>> def convert(input): 
...  try: 
...   templist=[int(ith) for ith in input.split('-')] 
...  except: 
...   templist=[] 
...  return templist 
...  
>>> convert('1-2-3-4') 
[1, 2, 3, 4] 
>>> convert('') 
[] 
>>> convert('----1-2--3--4---') 
[] 
>>> convert('Explicit is better than implicit.') 
[] 
>>> convert('1-1 = 0') 
[] 
0
def convert(s): 
    if s: 
     return map(int, s.split("-")) 
    else: 
     return [] 
0

你不需要的拉姆達和拆分不會給你空元素:

map(int, filter(None,x.split("-"))) 
+0

不幸的是,這打破了空弦。 – mipadi 2009-09-25 19:32:51

+0

嗯......我沒有注意到,如果輸入是一個空字符串(我認爲它返回一個空列表),split會返回一個空字符串。用過濾器修復 – fortran 2009-09-25 22:37:42

1

我會去這個:

>>> the_string = '1-2-3-4- -5- 6-' 
>>> 
>>> [int(x.strip()) for x in the_string.split('-') if len(x)] 
[1, 2, 3, 4, 5, 6] 
相關問題