【问题标题】:Appending keyword None to sublists in lists将关键字 None 附加到列表中的子列表
【发布时间】:2016-03-03 04:44:44
【问题描述】:

我想将关键字 None 附加到列表中。

  1. 如果输入列表中的元素个数 小于 rows*columns 然后用关键字 None 填充二维列表。
  2. 如果输入列表中的元素个数大于 rows*columns 然后忽略多余的元素。

对于给定try_convert_1D_to_2D([1, 2, 3, 4], 3, 4) 的输入,我想实现这样的目标:[[1, 2, 3, 4], [None, None, None, None], [None, None, None, None]]

我尝试的是:

def try_convert_1D_to_2D(my_list, r, c):
    a=r*c
    b=len(my_list)
    if(b >= a):
        l=[my_list[i:i+c] for i in range(0,b,c)]
        return l[0:r]
    else:
        for i in range(0,b,c):
            k=my_list[i:i+c]
            return [k.append(None) for k in a]

对于输入

try_convert_1D_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3) 

我可以达到[[8, 2, 9],[4, 1, 6]],这是正确的。

有人可以告诉我我在哪里做错了,请建议我如何做到最好。谢谢。

【问题讨论】:

  • 请提供与预期不符的结果。
  • 郑重声明,在 listcomp 中使用k.append(None) 几乎肯定会导致问题; list.append 不返回list,它只返回None,因此listcomp 只返回一个list,相当于你执行[None] * len(a) 时得到的结果。 listcomp 还覆盖/忽略了您之前仅定义一行的k

标签: list python-3.x append


【解决方案1】:

我指出several issues in the comments,这是一个真正有效的版本:

def try_convert_1D_to_2D(my_list, r, c):
    # Pad with Nones to necessary length
    padded = my_list + [None] * max(0, (r * c - len(my_list)))
    # Slice out rows at a time in a listcomp until we have what we need
    return [padded[i:i+c] for i in range(0, r*c, c)]

【讨论】:

  • 非常感谢您的回答并纠正代码中的错误。
猜你喜欢
  • 2022-01-06
  • 2014-02-14
  • 2014-06-07
  • 2012-12-20
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2019-03-29
  • 2015-07-03
相关资源
最近更新 更多