将所有字符串都转换为小写或大写的Python列表

问题:将所有字符串都转换为小写或大写的Python列表

我有一个包含字符串的python列表变量。是否有一个python函数可以将所有字符串一次转换为小写,反之亦然(大写)?

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?


回答 0

可以使用列表推导来完成。这些基本上采取的形式[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']

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

回答 1

除了易于阅读(对于许多人而言)之外,列表理解还赢得了速度竞赛:

$ 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

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

回答 2

>>> map(str.lower,["A","B","C"])
['a', 'b', 'c']
>>> map(str.lower,["A","B","C"])
['a', 'b', 'c']

回答 3

列表理解是我要做的,这是“ Pythonic”的方式。以下记录显示了如何将列表转换为全部大写然后转换回小写:

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

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

回答 4

对于此样本,理解最快

$ python -m timeit -s's = [“一个”,“两个”,“三个”] * 1000''[x.s中x的x.upper]
1000次循环,最好是3次:每个循环809微秒

$ python -m timeit -s's = [“一个”,“两个”,“三个”] * 1000''map(str.upper,s)'
1000次循环,每循环3:1.12毫秒的最佳时间

$ python -m timeit -s's = [“一个”,“两个”,“三个”] * 1000''map(lambda x:x.upper(),s)'
1000个循环,每个循环最好3:1.77毫秒

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

回答 5

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

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

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)

回答 6

mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three']
print(list(map(lambda x: x.lower(), mylist)))
print(list(map(lambda x: x.upper(), mylist)))
mylist = ['Mixed Case One', 'Mixed Case Two', 'Mixed Three']
print(list(map(lambda x: x.lower(), mylist)))
print(list(map(lambda x: x.upper(), mylist)))

回答 7

解:

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

此解决方案将创建一个单独的列表,其中包含小写字母的项目,无论它们的原始大小写如何。如果原始大小写为大写,则中的list s会包含相应项目的小写list p。如果列表项的原始大小写已经为小写,list plist s它将保留该项目的大小写并将其保持为小写。现在,您可以使用list s代替list p

Solution:

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

This solution will create a separate list containing the lowercase items, regardless of their original case. If the original case is upper then the list s will contain lowercase of the respective item in list p. If the original case of the list item is already lowercase in list p then the list s will retain the item’s case and keep it in lowercase. Now you can use list s instead of list p.


回答 8

如果您的目的是通过一次转换来与另一个字符串匹配,则也可以使用str.casefold()

(:集体VS集体EG).Though当你有非ASCII字符和匹配使用ASCII版本,这是有用str.lower还是str.upper在这种情况下出现故障时,str.casefold()会通过。这在Python 3中可用,并且通过回答https://stackoverflow.com/a/31599276/4848659详细讨论了这个想法。

>>>str="Hello World";
>>>print(str.lower());
hello world
>>>print(str.upper());
HELLO WOLRD
>>>print(str.casefold());
hello world

If your purpose is to matching with another string by converting in one pass, you can use str.casefold() as well.

This is useful when you have non-ascii characters and matching with ascii versions(eg: maße vs masse).Though str.lower or str.upper fails in such cases, str.casefold() will pass. This is available in Python 3 and the idea is discussed in detail with the answer https://stackoverflow.com/a/31599276/4848659.

>>>str="Hello World";
>>>print(str.lower());
hello world
>>>print(str.upper());
HELLO WOLRD
>>>print(str.casefold());
hello world

回答 9

@Amorpheuses 在此处给出了最简单答案的顶级答案。

带有val中的值列表:

valsLower = [item.lower() for item in vals]

对于f = open()文本源,这对我来说效果很好。

A much simpler version of the top answer is given here by @Amorpheuses.

With a list of values in val:

valsLower = [item.lower() for item in vals]

This worked well for me with an f = open() text source.


回答 10

您可以尝试使用:

my_list = ['india', 'america', 'china', 'korea']

def capitalize_list(item):
    return item.upper()

print(list(map(capitalize_list, my_list)))

You could try using:

my_list = ['india', 'america', 'china', 'korea']

def capitalize_list(item):
    return item.upper()

print(list(map(capitalize_list, my_list)))

回答 11

的Python3.6.8

In [1]: a = 'which option is the fastest'                                                                                                                                           

In [2]: %%timeit 
   ...: ''.join(a).upper() 
762 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %%timeit  
   ...: map(lambda x:x.upper(), a) 
209 ns ± 5.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %%timeit  
   ...: map(str.upper, [i for i in a]) 
1.18 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [5]: %%timeit 
   ...: [i.upper() for i in a] 
3.2 µs ± 64.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

如果您需要一个字符串或列表作为输出而不是一个迭代器(这是针对Python3的),则可以使用compare ''.join(string).upper()选项:

In [10]: %%timeit  
    ...: [i for i in map(lambda x:x.upper(), a)] 
4.32 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Python3.6.8

In [1]: a = 'which option is the fastest'                                                                                                                                           

In [2]: %%timeit 
   ...: ''.join(a).upper() 
762 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %%timeit  
   ...: map(lambda x:x.upper(), a) 
209 ns ± 5.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %%timeit  
   ...: map(str.upper, [i for i in a]) 
1.18 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [5]: %%timeit 
   ...: [i.upper() for i in a] 
3.2 µs ± 64.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

If you need a string or list as the output and not an iterator (this is for Python3), compare ''.join(string).upper() option to this:

In [10]: %%timeit  
    ...: [i for i in map(lambda x:x.upper(), a)] 
4.32 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

回答 12

如果您尝试将列表中的所有字符串都转换为小写,则可以使用pandas:

import pandas as pd

data = ['Study', 'Insights']

pd_d = list(pd.Series(data).str.lower())

输出:

['study', 'insights']

If you are trying to convert all string to lowercase in the list, You can use pandas :

import pandas as pd

data = ['Study', 'Insights']

pd_d = list(pd.Series(data).str.lower())

output:

['study', 'insights']