代码之家  ›  专栏  ›  技术社区  ›  Kashvi

我的答案不是为其中一个样本运行

  •  -1
  • Kashvi  · 技术社区  · 2 年前

    我使用列表理解编写了这个python3代码,我的代码在其中一个示例中运行良好,但在答案中显示了一个额外的列表,如所附图片所示。 它在答案中显示[1,1,0],而不应该显示。

    我更改了范围,甚至将==符号更改为!=并将remove更改为append,但随后它显示了一些其他错误。

    问题:

    打印一个不等于n的元素数组 输入格式 四个整数x、y、z和n,每一个都在一条单独的线上。 限制 按字典递增顺序打印列表。

    代码:

    if __name__ == '__main__':
    a = int(input())
    b = int(input())
    c = int(input())
    n = int(input())
    list1=[[x,y,z] for x in range(a+1) for y in range(b+1) for z in range(c+1)]
    for i in list1:
        if sum(i)== n:
            list1.remove(i)
    print(list1)
    

    示例:

    输入: 1. 1. 1. 2.

    我的输出: [[0,0,0],[0,1,0],[1,0,0]]

    预期输出: [[0,0,0],[0],0,1],[0,1,0],[1,0,0],[1,1,1]

    1 回复  |  直到 2 年前
        1
  •  0
  •   Galo Torres Sevilla    2 年前

    这就是你要找的吗?

    a = int(input())
    b = int(input())
    c = int(input())
    n = int(input())
    
    l = [[x,y,z] for x in range(a+1) for y in range(b+1) for z in range(c+1) if (x+y+z) != n]
    print(l)
    
        2
  •  0
  •   Xinthral    2 年前

    为了回答您的问题,我将使用另一个列表理解:

    list2 = [s for s in list1 if not sum(s) == n]

    现在list2包含您想要的所有文件:

    >> ./testnum.py 
    1
    1
    1
    2
    [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
    New stuff
    [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]