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

标签 python

我正在尝试将列表中的元素转换为小写。这就是它的样子。

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

关于python - 如何将列表列表中的元素转换为小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540718/

相关文章:

python - 使用 python statsmodels 设置 ADF 测试的 maxlag 不起作用?

python - 从 Webscrape 中过滤和格式化数据帧

python - 无法在 Pandas 数据框中进行插值

python - QMediaContent 如何在 urllib 无法下载时显示视频?

python - Jupyter 笔记本 : duplicated scatter plot using when using ipywidgets

python - 如何使用 python 对 CSV 文件的多列进行排序?

python - Google Cloud Functions - 我可以将来自不同 GCP 项目存储库的代码部署到 Cloud Functions 中吗?

python - 如何为 Mercurial Hooks 的 pyCharm 设置 python 解释器

python - 如何删除python列表中的对象

python - 使用python以循环方式裁剪图像