【问题标题】:Replace character if list index is out of range如果列表索引超出范围,则替换字符
【发布时间】:2020-11-14 13:27:52
【问题描述】:

我有一个清单:

['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']

我想像这样打印每三个项目:

['5', '16', '12', '2', '1', '']

但由于空字符串,最后一项导致索引列表超出范围。 我想要的是将所有空字符串替换为0

所以我想要的结果是这样的:

['5', '16', '12', '2', '1', '0']

我不知道该怎么做。这是我正在尝试做的一部分:

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
actual = [item.split()[2] for item in carac_list]

print("Actual = " + str(actual))

【问题讨论】:

  • 为什么只有一个 0 而不是两个 - 来自'2 3 ' 和来自''
  • 是的,它可能是两个 0,最后一个空列表是我必须删除的东西,我的想法是,如果第三个字符为空,则列表将其替换为 0 或两个。

标签: python list


【解决方案1】:

可以使用Python3.8中引入的Assignment Expressions/walrus operator

carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
actual = [y[2] if len(y) == 3 else '0' for item in carac_list if (y := item.split())]
print(actual)

输出:

['5', '16', '12', '2', '1', '0']

【讨论】:

    【解决方案2】:

    与其他一些类似,但在列表推导中只有一个 if 和一个 for,在 Python 3.8+ 中使用海象运算符

    carac_list = ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
    out = [y[2] if len(y := x.split()) >= 3 else "0" for x in carac_list]
    
    ['5', '16', '12', '2', '1', '0', '0']
    

    【讨论】:

      【解决方案3】:
      >>> seq
      ['21 25 5', '16 20 16', '16 20 12', '7 10 2', '2 3  1 ', '2 3   ', '']
      >>> [i[0] if i else '0' for i in (i.split()[2:] for i in seq)]
      ['5', '16', '12', '2', '1', '0', '0']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 2011-06-14
        • 2016-06-04
        • 1970-01-01
        相关资源
        最近更新 更多