I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
It can be done with list comprehensions. These basically take the form of [function-of-item for item in some-list]. For example, to create a new list where all the items are lower-cased (or upper-cased in the second snippet), you would use:
>>> [x.lower() for x in ["A","B","C"]] ['a', 'b', 'c'] >>> [x.upper() for x in ["a","b","c"]] ['A', 'B', 'C'] You can also use the map function:
>>> map(lambda x:x.lower(),["A","B","C"]) ['a', 'b', 'c'] >>> map(lambda x:x.upper(),["a","b","c"]) ['A', 'B', 'C'] 回答2:
Besides being easier to read (for many people), list comprehensions win the speed race, too:
$ 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 回答3:
>>> map(str.lower,["A","B","C"]) ['a', 'b', 'c'] 回答4:
List comprehension is how I'd do it, it's the "Pythonic" way. The following transcript shows how to convert a list to all upper case then back to lower:
pax@paxbox7:~$ python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = ["one", "two", "three"] ; x ['one', 'two', 'three'] >>> x = [element.upper() for element in x] ; x ['ONE', 'TWO', 'THREE'] >>> x = [element.lower() for element in x] ; x ['one', 'two', 'three'] 回答5:
For this sample the comprehension is fastest
$ python -m timeit -s 's=["one","two","three"]*1000' '[x.upper for x in s]' 1000 loops, best of 3: 809 usec per loop $ python -m timeit -s 's=["one","two","three"]*1000' 'map(str.upper,s)' 1000 loops, best of 3: 1.12 msec per loop $ python -m timeit -s 's=["one","two","three"]*1000' 'map(lambda x:x.upper(),s)' 1000 loops, best of 3: 1.77 msec per loop
回答6:
mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three'] print map(lambda x: x.lower(), mylist) print map(lambda x: x.upper(), mylist) 回答7:
a student asking, another student with the same problem answering :))
fruits=['orange', 'grape', 'kiwi', 'apple', 'mango', 'fig', 'lemon'] newList = [] for fruit in fruits: newList.append(fruit.upper()) print(newlist)