使用列表理解将主题标签应用于列表中不存在主题标签的项目

Using list comprehension to apply hashtag to items in list where hashtag is not present

我正在尝试理解和探索如何在列表理解中编写条件:

我想将以下 for 循环转换为列表推导式:

    dot = ['.hello', 'world']

    for i in range(len(dot)):
        if dot[i][0] != ".":
            dot[i] = "." + dot[i]

我相信我一定是错误地应用了描述的格式 here:

test = ["." + x for x in dot if dot[x][0] != "."]

... 并因此收到以下内容:

TypeError: list indices must be integers or slices, not str

我完全理解可读性会受到影响 - 我只是为了自己的学习而尝试列表理解。

[x if x.startswith('.') else '.' + x for x in dot]

是在列表理解中执行此操作的正确方法。

您在循环中寻址 dot 不正确。

test = ["." + x for x in dot if dot[x][0] != "."]

x in dot 是列表中的元素,一个字符串。您不能使用 strings 访问列表中的索引。

您无法从列表理解内部更新列表 - 理解表达式 returns 一个新列表。因此,与其考虑 dot[some_index],不如考虑列表中的元素 x,以及您要用它做什么:

result = ['.' + x if x[0] != '.' else x  for x in dot]