如何使用 Python itertools 删除整数元组中的最后一个元素为“0”的元组?

ser*_*lik 4 python list-comprehension python-itertools

我有以下代码来创建一个包含多个带有整数对的元组的元组:

iterable = (
    tuple(zip([0, 1, 2], _))
    for _ in product(range(9), repeat=3)
)
next(iterable)  # First element is not needed
print(list(iterable))

# This code produces: [((0, 0), (1, 0), (2, 1)), ... , ((0, 8), (1, 8), (2, 8))]
Run Code Online (Sandbox Code Playgroud)

但我需要,如果元组的最后一个元素是“0”(例如(0, 0)或(2, 0)),我必须删除该元组。所以新的列表应该是这样的:

[((2, 1),), ... , ((1, 2), (2, 7)), ((1, 2), (2, 8)), ... , ((0, 8), (1, 8), (2, 8))]
Run Code Online (Sandbox Code Playgroud)

我实际上通过以下代码实现了这个目标,但这不是我认为的正确方法,我不知道:

x = ()
for i in iterable:
    y = ()
    for j in i:
        if j[-1] != 0:
            y += (j,)
    x += (y,)
print(list(x))
Run Code Online (Sandbox Code Playgroud)

如果可能的话,如何使用itertools模块并在一行中完成此操作?如果需要,我可以更改此问题顶部的代码,以在一行中创建所需的列表。

谢谢。

Bar*_*mar 6

用于从 的结果filter()中删除以 结尾的元素。0zip()

iterable = (
    tuple(filter(lambda x: x[-1] != 0, zip([0, 1, 2], _)))
    for _ in product(range(9), repeat=3)
)
Run Code Online (Sandbox Code Playgroud)

  • 此代码给出错误“NameError:名称't'未定义”。 (3认同)