2011-04-27 135 views

回答

5
''.join(c.lower() for c in s if not c.isspace()) 

不.Python不是Ruby。

+0

是正則表達式的東西是在Python用得少? – 2011-04-27 04:04:11

+1

正則表達式通常不是必需的。 – 2011-04-27 04:05:43

+2

@DutrowLLC,它們通常不是必需的,但有時它們是不可或缺的。 – ghostdog74 2011-04-27 04:07:49

2
>>> string=""" a b  c 
... D E   F 
...      g 
... """ 
>>> ''.join( i.lower() for i in string.split() ) 
'abcdefg' 
>>> 

OR

>>> ''.join(map(str.lower, string.split()) ) 
'abcdefg' 
+0

您的加入拆分解決方案仍然比John Machin的答案慢很多,使用timeit將其時鐘數設置爲0.733391046524s,對於250k代表,對於他的解決方案,則爲0.413959026337s。以最快的速度前進! – radtek 2017-08-05 03:53:39

1

這裏使用的解決方案正則表達式:

>>> import re 
>>> test = """AB cd KLM 
    RST l 
    K""" 
>>> re.sub('\s+','',test).lower() 
    'abcdklmrstlk' 

+0

這似乎是最慢的一組,在250k迭代中的0.809034109116s與John Machin的解決方案在0.411396980286s。地圖也比0.582627058029s更快。 – radtek 2017-08-05 03:47:10

18

怎麼樣一個簡單快速答案嗎?沒有map,沒有for環路,...

>>> s = "Foo Bar " * 5 
>>> s 
'Foo Bar Foo Bar Foo Bar Foo Bar Foo Bar ' 
>>> ''.join(s.split()).lower() 
'foobarfoobarfoobarfoobarfoobar' 
>>> 

[Python的2.7.1]

>python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(c.lower() for c in s if not c.isspace())" 
100000 loops, best of 3: 11.7 usec per loop 

>python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join( i.lower() for i in s.split() )" 
100000 loops, best of 3: 3.11 usec per loop 

>python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(map(str.lower, s.split()) )" 
100000 loops, best of 3: 2.43 usec per loop 

>\python27\python -mtimeit -s"s='The quick brown Fox jumped over the lazy dogs'" "''.join(s.split()).lower()" 
1000000 loops, best of 3: 1 usec per loop 
+0

+1不妨使用最快,最正確的選項。 – samplebias 2011-04-27 21:56:10

+0

+1,確實是我目前看到的最快的。用timeit模塊確認使用250k迭代0.403948068619s使用split,0.585318088531s使用map。謝謝! – radtek 2017-08-05 03:43:38

相關問題