【问题标题】:Editing a list in Python在 Python 中编辑列表
【发布时间】:2020-08-05 21:30:58
【问题描述】:

这是我写的代码:

lines = ['add something to this line',
         'add nothing to this one',
         'emphasize this line',
         'emphasize nothing, instead remove a "count" number of characters from the end']

count = 0
new_lines = []
for n,line in enumerate(lines):
    if n > 0:
        if lines[n-1][:4] == line[:4]:
            new_lines.pop(-1)
            new_lines.append(lines[n-1] + '!!!')
            count += 3
    elif n == len(lines)-1:
        line = line[:-count]
    new_lines.append(line)

new_lines 很好,但对于最后一行。不应该被截断吗?

['add something to this line!!!',
 'add nothing to this one',
 'emphasize this line!!!',
 'emphasize nothing, instead remove a "count" number of characters from the end']

编辑:我的意思是写len(lines),而不是len(new_lines)

【问题讨论】:

    标签: python list loops for-loop indexing


    【解决方案1】:

    看看你的逻辑:

    if n > 0:
        ...
    elif n == len(new_lines)-1:
        line = line[:-count]
    

    首先,这只能在列表的 first 行上起作用:在那之后,n 是肯定的,所以你不会得到这个else 部分。对于您希望更改的行,n 是 3,因此您被困在 if/True 子句中。

    接下来,n 始终等于 len(此时为 new_lines)。您的 elif 条件在代数上为 False。

    如果你想改变最后一行,试试

    if n == len(lines)-1:
    

    输出:

    add something to this line!!!
    add nothing to this one
    emphasize this line!!!
    emphasize nothing, instead remove a "count" number of characters from t
    

    【讨论】:

      【解决方案2】:

      不,因为elif n == len(new_lines)-1: 永远不会是True。以下是实际值:

      n, len(new_lines)-1
      0, -1
      1, 0
      2, 1
      3, 2
      

      在第一次迭代之后,if n > 0: 将永远是True,所以你永远不会进入这个块:elif n == len(lines)-1:。将 elif 更改为 if 即可获得所需的行为。

      【讨论】:

      • 我想我是想说 len(lines),抱歉。它也输出相同类型的列表。
      猜你喜欢
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 2018-03-08
      • 2011-03-06
      • 2021-03-30
      • 2023-03-20
      相关资源
      最近更新 更多