小编ser*_*lik的帖子

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

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

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] …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension python-itertools

4
推荐指数
1
解决办法
127
查看次数