我有一个包含字符串的Python列表变量。是否有一个函数,可以转换所有的字符串在一个传递小写,反之亦然,大写?


当前回答

解决方案:

>>> 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']

此解决方案将创建一个单独的列表,其中包含小写项,而不管它们的原始大小写。如果原始的大小写是大写,那么列表s将包含列表p中相应项的小写。如果列表p中列表项的原始大小写已经是小写,那么列表s将保留该项的大小写并保持其小写。现在你可以用列表s代替列表p。

其他回答

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

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

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

$ 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

除了更容易阅读(对许多人来说),列表推导式也在速度竞赛中获胜:

$ 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

列表理解是我的做法,这是“python”的方式。下面的文字记录展示了如何将一个列表全部转换为大写,然后再转换回小写:

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']

解决方案:

>>> 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']

此解决方案将创建一个单独的列表,其中包含小写项,而不管它们的原始大小写。如果原始的大小写是大写,那么列表s将包含列表p中相应项的小写。如果列表p中列表项的原始大小写已经是小写,那么列表s将保留该项的大小写并保持其小写。现在你可以用列表s代替列表p。