Convert a Python list with strings all to lowercase or uppercase
我有一个包含字符串的python list变量。是否有一个python函数可以将一次传递中的所有字符串转换为小写,反之亦然(大写)?
它可以通过列表理解来完成。这些基本上是以
1 2 3 4 5 | >>> [x.lower() for x in ["A","B","C"]] ['a', 'b', 'c'] >>> [x.upper() for x in ["a","b","c"]] ['A', 'B', 'C'] |
您还可以使用
1 2 3 4 | >>> map(lambda x:x.lower(),["A","B","C"]) ['a', 'b', 'c'] >>> map(lambda x:x.upper(),["a","b","c"]) ['A', 'B', 'C'] |
除了更容易阅读(对很多人来说),列表理解也赢得了速度竞赛:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $ 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 |
1 2 | >>> map(str.lower,["A","B","C"]) ['a', 'b', 'c'] |
单子理解就是我该怎么做,这是"Python"的方式。下面的文字说明如何将列表转换为所有大写,然后再转换回小写:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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'] |
对于这个例子,理解速度最快
1 2 3 4 5 6 7 8 | $ 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 |
一个学生问,另一个有同样问题的学生回答:)
1 2 3 4 5 | fruits=['orange', 'grape', 'kiwi', 'apple', 'mango', 'fig', 'lemon'] newList = [] for fruit in fruits: newList.append(fruit.upper()) print(newlist) |
1 2 3 | mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three'] print map(lambda x: x.lower(), mylist) print map(lambda x: x.upper(), mylist) |
如果您的目的是通过一次转换来匹配另一个字符串,那么也可以使用
当您使用非ASCII字符并与ASCII版本(例如:MA)匹配时,这很有用。e vs masse)虽然
1 2 3 4 5 6 7 | >>>str="Hello World"; >>>print(str.lower()); hello world >>>print(str.upper()); HELLO WOLRD >>>print(str.casefold()); hello world |
解决方案:
1 2 3 4 5 | >>> s = [] >>> p = ['This', 'That', 'There', 'is', 'apple'] >>> [s.append(i.lower()) if not i.islower() else s.append(i) for i in p] >>> s >>> ['this', 'that', 'there', 'is','apple'] |
此解决方案将创建一个单独的列表,其中包含小写项,而不考虑它们的原始大小写。如果原始大小写为大写,则