Python 用字符串列表中每个字符串的前两个字母制作一个列表

Python 用字符串列表中每个字符串的前两个字母制作一个列表,python,Python,用字符串列表中每个字符串的前两个字母制作列表的最佳方法是什么。比如说我有 L = ['apple','banana','pear'] 我希望结果是 ['ap','ba','pe'] 没问题: L = ['apple','banana','pear'] [s[:2] for s in L] 如果L的一项为空,则可以添加 [ s[:2] for s in L if s] 你可以使用列表理解法 >>> L = ['apple', 'banana', 'pear'] >

用字符串列表中每个字符串的前两个字母制作列表的最佳方法是什么。比如说我有

L = ['apple','banana','pear']
我希望结果是

['ap','ba','pe']
没问题:

L = ['apple','banana','pear']
[s[:2] for s in L]
如果L的一项为空,则可以添加

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

你可以使用列表理解法

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

虽然所有其他答案都应该是首选,但这里只是作为一个备选解决方案,希望它会让你感兴趣

您可以使用传递对象的函数创建列表:

>>> import operator
>>> L = ['apple','banana','pear']
>>> map(operator.getitem, L, (slice(0, 2), ) * len(L))
['ap', 'ba', 'pe']
或者,您可以使用并调用_getitem _; magic方法:

>>> import operator
>>> f = operator.methodcaller('__getitem__', slice(0, 2))
>>> map(f, L)
['ap', 'ba', 'pe']
请注意,这两种解决方案都不适合实际使用,因为它们至少比基于列表理解的方法更慢,可读性更低。

[s[:2]表示L中的s]?
>>> import operator
>>> f = operator.methodcaller('__getitem__', slice(0, 2))
>>> map(f, L)
['ap', 'ba', 'pe']