将包含字符串的Python列表全部转换为小写或大写

2024-04-18 22:33:22 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
>>> map(str.lower,["A","B","C"])
['a', 'b', 'c']

除了容易阅读(对许多人来说),列表理解也赢得了速度竞赛:

$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'
1000000 loops, best of 3: 1.03 usec per loop
$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'
1000000 loops, best of 3: 1.04 usec per loop

$ python2.6 -m timeit 'map(str.lower,["A","B","C"])'
1000000 loops, best of 3: 1.44 usec per loop
$ python2.6 -m timeit 'map(str.upper,["a","b","c"])'
1000000 loops, best of 3: 1.44 usec per loop

$ python2.6 -m timeit 'map(lambda x:x.lower(),["A","B","C"])'
1000000 loops, best of 3: 1.87 usec per loop
$ python2.6 -m timeit 'map(lambda x:x.upper(),["a","b","c"])'
1000000 loops, best of 3: 1.87 usec per loop

它可以通过列表理解来完成。它们基本上以[function-of-item for item in some-list]的形式出现。例如,要创建一个新列表,其中所有项都是小写(或第二个代码片段中的大写),您可以使用:

>>> [x.lower() for x in ["A","B","C"]]
['a', 'b', 'c']

>>> [x.upper() for x in ["a","b","c"]]
['A', 'B', 'C']

您还可以使用map函数:

>>> map(lambda x:x.lower(),["A","B","C"])
['a', 'b', 'c']
>>> map(lambda x:x.upper(),["a","b","c"])
['A', 'B', 'C']

相关问题 更多 >