【问题标题】:Please Help Explain This Code That Removes Leading Zeros (EPI-Python)请帮助解释删除前导零的代码(EPI-Python)
【发布时间】:2020-11-06 03:16:03
【问题描述】:
res = [0,0,1,2,3]
res = res[next((i for i, x in enumerate(res) if x != 0), len(res)):] or [0]
# res => [1,2,3]

有人可以解释一下res[next((i for i, x in enumerate(res) if x != 0), len(res)):] or [0] 在做什么吗?谢谢!

【问题讨论】:

    标签: python arrays algorithm sorting


    【解决方案1】:

    一行代码的扩展版是

    index = len(res) # initialize the index
    for i, r in enumerate(res): # find index to the first non-zero element
        if r != 0:
            index = i
            break
    # if there is no non-zero element, index will be pointed to len(res)
    res = res[index:] # remove all non-zero leading element
    if len(res) == 0:
        res = [0] # if there is no non-zero element
    

    这个想法是从数组中删除所有前导非零元素,如果所有元素都为零,则只保留一个。

    [0,0,1] => [1]

    [1,2,0] => [1,2,0]

    [0,0,0] => [0]

    【讨论】:

      【解决方案2】:

      添加到@Burning Alcohol 的答案,

      1. (i for i, x in enumerate(res) if x != 0) 创建一个迭代器,相当于iter([2,3,4])
      2. next((i for i, x in enumerate(res) if x != 0)会显示迭代器的第一个元素,由于迭代器是[2,3,4],所以第一个元素是2
      3. res[next((i for i, x in enumerate(res) if x != 0), len(res)):]res[2:] 相同,相当于“2 to end”,这给了我们 [1,2,3]

      我刚开始学习 Python,这真的很酷,谢谢大家!

      【讨论】:

      • 很高兴您发现这种有用且快乐的编码!
      猜你喜欢
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多