我正在尝试将列表中的元素转换为小写。这就是它的样子。
print(dataset)
[['It', 'went', 'Through', 'my', 'shirt', 'And', 'came', 'out', 'The', 'back', 'and', 'hit', 'the', 'kid', 'behind', 'me', 'in', 'the', 'toe']]
我试过这样做:
for line in dataset:
rt=[w.lower() for w in line]
然而,这给了我一个错误,说列表对象没有属性 lower()。
您有一个嵌套结构。展开(如果只包含一个列表,永远)或使用嵌套列表理解:
[[w.lower() for w in line] for line in dataset]
嵌套列表理解分别处理 dataset
列表中的每个 list
。
如果dataset
中只有一个 列表,您也可以解包:
[w.lower() for w in dataset[0]]
这会生成一个直接包含小写字符串的列表,而无需进一步嵌套。
演示:
>>> 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']