有没有办法在python中删除列表?

qed*_*qed 3 python data-structures

我正在寻找一种潜入列表并直接访问其元素的方法.例如,以下是获取集合的笛卡尔乘积的常规方法.

>>> list(itertools.product((0,1), (0,1),(0,1),(0,1)))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下,这四个套装是相同的,很快就会一次又一次地输入它而变得无聊和烦人,这让人想到这样做:

>>> list(itertools.product([(0,1)]*4)
Run Code Online (Sandbox Code Playgroud)

但当然它不起作用,因为itertools.product函数会将其视为一组而不是四组.所以,问题是,有没有办法做到这一点:

>>> list(itertools.product(delist([(0,1)]*4))
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 9

itertools.product((0,1), repeat=4)
Run Code Online (Sandbox Code Playgroud)

product函数接受可选repeat参数.以上相当于itertools.product((0, 1), (0, 1), (0, 1), (0, 1)).


一般来说,如果你有一个清单

lst = [1, 2, 4, 6, 8, ...]
Run Code Online (Sandbox Code Playgroud)

你想把一个函数称为

f(1, 2, 4, 6, 8, ...)
Run Code Online (Sandbox Code Playgroud)

你可以使用*(解压缩)运营商展开列表为参数列表:

f(*lst)
Run Code Online (Sandbox Code Playgroud)


Har*_*wEm 5

如果您不使用itertools.product,您也可以使用*运算符。该*运营商做什么我想你的意思是“摘牌”。它将列表或其他可迭代对象的内容转换为函数的位置参数。一般来说:

args = ['arg1', 'arg2', 'arg3', 'arg4']

# The following two calls are exactly equivalent
func('arg1', 'arg2', 'arg3', 'arg4')
func(*args)
Run Code Online (Sandbox Code Playgroud)

在此特定示例中,代码如下所示:

itertools.product(*[(0,1)]*4)
Run Code Online (Sandbox Code Playgroud)

但是,在以下特定情况下,先前的答案(由 KennyTM 提供)可能更清晰itertools.product

itertools.product((0, 1), repeat=4)
Run Code Online (Sandbox Code Playgroud)