Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将列表转换为小写_Python_List - Fatal编程技术网

在Python中将列表转换为小写

在Python中将列表转换为小写,python,list,Python,List,我不明白为什么我只能得到原始列表的最后一个字符串?thx documents = ['Hello, how are you!', 'Win money, win from home.', 'Call me now.', 'Hello, Call hello you tomorrow?'] lc =[] for x in documents: lc = x.lower() print (lc) Out:

我不明白为什么我只能得到原始列表的最后一个字符串?thx

documents = ['Hello, how are you!',
             'Win money, win from home.',
             'Call me now.',
             'Hello, Call hello you tomorrow?']

lc =[]
for x in documents:
    lc = x.lower()

print (lc)  
Out: hello, call hello you tomorrow?

您的代码首先将
lc
分配给一个空数组。然后在原始数组上循环,每次都会丢弃分配给
lc
的任何内容(从未使用的空数组开始),并用该字符串的小写版本替换它。最后,您使用最后一个字符串的小写版本离开
lc
;其他一切都被丢弃了

相反,您要做的是从旧阵列构建一个新阵列。python的方法是使用列表理解

lc = [x.lower() for x in documents]
这将生成一个新数组,其中包含原始数组中每个元素的小写版本:

>>> lc
['hello, how are you!', 'win money, win from home.', 
 'call me now.', 'hello, call hello you tomorrow?']
lc=x.lower()
在每次迭代中重新分配。您需要将其附加到空列表
lc
方式1:列表理解

[x.lower() for x in documents]

['hello, how are you!',
 'win money, win from home.',
 'call me now.',
 'hello, call hello you tomorrow?']
对于文档中的x
:将迭代列表中的所有字符串

x.lower()
:将转换为小写


方式2:您的代码:

lc =[]
for x in documents:
    lc.append(x.lower()) # append to the initially empty list
print(lc)

['hello, how are you!', 'win money, win from home.', 'call me now.', 'hello, call hello you tomorrow?']

不同的方法你可以用它列出他的

ls=list(映射(lambda x:x.lower(),文档))


或者map会返回一个生成器,以便您在从文档中读取列表时可以对其进行迭代。如果您使用的是非常大的文件,则可以派上用场。等等

这是因为您只有一个
lc
,当您说
lc=x.lower()
时,您一直用一个全新的值替换它。因此,它以您指定的最后一个值结束。相反,您要做的是将每个
x.lower()
追加到已经是
lc
lc.append(x.lower())
的数组中。非常感谢。在带有
lambda的
映射()上的
列表()
?为什么不使用列表理解…?只是另一种方法。。对象列表组件。这是最好的办法。。