2014-08-27 84 views

回答

1

沒有問題:

L = ['apple','banana','pear'] 
[s[:2] for s in L] 
1
L = ['apple','banana','pear'] 
[ s[:2] for s in L ] 

如果L的一個項目是空的,您可以添加

[ s[:2] for s in L if s] 
1

你可以使用列表理解爲

>>> L = ['apple', 'banana', 'pear'] 
>>> newL = [item[:2] for item in L] 
>>> print newL 
['ap', 'ba', 'pe'] 
0

雖然所有其他的答案應該是首選,這裏只是作爲一種替代解決方案,希望看起來有趣的爲您服務。

您可以operator.getitem()功能與slice對象通過map名單:

>>> import operator 
>>> L = ['apple','banana','pear'] 
>>> map(operator.getitem, L, (slice(0, 2),) * len(L)) 
['ap', 'ba', 'pe'] 

或者,你可以使用operator.methodcaller(),並調用__getitem__()魔術方法:

>>> import operator 
>>> f = operator.methodcaller('__getitem__', slice(0, 2)) 
>>> map(f, L) 
['ap', 'ba', 'pe'] 

注意,這兩種解決方案都沒有對實際的實際用法,因爲它們至少比基於列表理解的方法更慢和更不可讀。

相關問題