如何将列表列表中的元素转换为小写?

min*_*nks 1 python

我试图转换列表的小写列表的元素.这就是看起来像.

print(dataset)
[['It', 'went', 'Through', 'my', 'shirt', 'And', 'came', 'out', 'The', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
Run Code Online (Sandbox Code Playgroud)

我试过这样做:

for line in dataset:
    rt=[w.lower() for w in line]
Run Code Online (Sandbox Code Playgroud)

但是这给了我一个错误,说列表对象没有属性lower().

Mar*_*ers 12

你有一个嵌套的结构.解包(如果只包含一个列表)或使用嵌套列表解析:

[[w.lower() for w in line] for line in dataset]
Run Code Online (Sandbox Code Playgroud)

嵌套列表理解处理每个listdataset单独列表中.

如果你只包含一个列表dataset,你也可以解包:

[w.lower() for w in dataset[0]]
Run Code Online (Sandbox Code Playgroud)

这将生成一个列表,其中包含直接包含的小写字符串,而无需进一步嵌套.

演示:

>>> dataset = [['It', 'went', 'Through', 'my', 'shirt', 'And', 'came', 'out', 'The', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
>>> [[w.lower() for w in line] for line in dataset]
[['it', 'went', 'through', 'my', 'shirt', 'and', 'came', 'out', 'the', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
>>> [w.lower() for w in dataset[0]]
['it', 'went', 'through', 'my', 'shirt', 'and', 'came', 'out', 'the', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']
Run Code Online (Sandbox Code Playgroud)

  • @Falko:在Python 2中,是的.在Python 3中,你必须添加`list()`.我更喜欢这里的列表理解,无论如何,我发现它更具可读性.列表理解还支持开箱即用的"str"和"unicode"对象的混合. (2认同)