gpt4 book ai didi

python - 使用列表理解更改嵌套列表中的第一项

转载 作者:行者123 更新时间:2023-11-28 20:36:45 24 4
gpt4 key购买 nike

假设我有以下列表:

[['Hello im an item', 1234], ['I enjoy python', 'hello'], ['I only have one item']]

我想在每个内部列表的第一项中用下划线替换空格,因此它看起来像这样:

[['Hello_im_an_item', 1234], ['I_enjoy_python', 'hello'], ['I_only_have_one_item']]

我已经尝试了以下但没有成功:

formatted = [first[0].replace(' ', '_') for first in formatted]

formatted 返回仅包含第一个项目的列表,但格式正确。有谁知道如何实现这一点?

最佳答案

列表理解构建了一个全新的列表,因此您需要确保新列表包含旧列表包含的所有内容。连接每个子列表的其余部分:

formatted = [[sub[0].replace(' ', '_')] + sub[1:] for sub in formatted]

作为一个普通的for循环,上面的代码大致等同于:

_new = []
for sub in formatted:
_element = [sub[0].replace(' ', '_')] + sub[1:]
_new.append(_element)
formatted = _new

与其使用列表理解,不如使用常规循环就地更改列表:

for sub in formatted:
sub[0] = sub[0].replace(' ', '_')

仅当您绝对需要一个全新的列表时才使用列表理解。

关于python - 使用列表理解更改嵌套列表中的第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44417847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com