将一个Python列表全部转换为小写或大写

我有一个包含string的Python列表variables。 有一个python函数可以将所有string转换为小写,反之亦然,大写?

这可以通过列表parsing来完成

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

或与地图function

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

除了易于阅读(对于许多人),列表parsing也赢得了速度竞赛:

 $ 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 
 >>> map(str.lower,["A","B","C"]) ['a', 'b', 'c'] 

列表parsing是我怎么做的。 下面的代码片段展示了如何将列表转换为全部大写,然后再转换为更低:

 $ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> list = ["one", "two", "three"] >>> list ['one', 'two', 'three'] >>> list = [element.upper() for element in list] >>> list ['ONE', 'TWO', 'THREE'] >>> list = [element.lower() for element in list] >>> list ['one', 'two', 'three'] 

对于这个例子,理解是最快的

 $ python -m timeit -s's = [“one”,“two”,“three”] * 1000''[x.upper for x in s]'
 1000循环,最好是每循环3:809次

 $ python -m timeit -s's = [“one”,“two”,“three”] * 1000''map(str.upper,s)'
 1000个循环,最好是3:1.12毫秒每个循环

 $ python -m timeit -s's = [“one”,“two”,“three”] * 1000''map(lambda x:x.upper(),s)'
 1000个循环,最好是3:1.77毫秒每个循环
 mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three'] print map(lambda x: x.lower(), mylist) print map(lambda x: x.upper(), mylist) 

一个学生问,另一个同样问题的学生回答:))

 fruits=['orange', 'grape', 'kiwi', 'apple', 'mango', 'fig', 'lemon'] newList = [] for fruit in fruits: newList.append(fruit.upper()) print(newlist)