有没有办法在 python 中删除列表?
我正在寻找一种方法来深入列表并直接访问其元素。例如,以下是获取 for 集合的笛卡尔积的正常方法。
>>> 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)]
但在这种情况下,这四组是相同的,并且很快就会变得无聊而令人厌烦,不得不一遍又一遍地输入它,这使得人们想到这样做:
>>> list(itertools.product([(0,1)]*4)
但当然它不会工作,因为 itertools.product函数会将其视为一组而不是四组。那么,问题是,有没有办法做到这一点:
>>> list(itertools.product(delist([(0,1)]*4))
I am looking for a method to dive into a list and directly access its elements. For example, the following is the normal way of getting the Cartesian product of for sets.
>>> 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)]
But in this case the four sets are identical, and it soon gets boring and tiresome to have to type it over and over again, which makes one think of doing this instead:
>>> list(itertools.product([(0,1)]*4)
But of course it won't work, since the itertools.product function will see it as one set instead of four sets. So, the question is, is there a way to do this:
>>> list(itertools.product(delist([(0,1)]*4))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
product
函数接受可选的repeat< /code> 参数
。上面等价于
itertools.product((0, 1), (0, 1), (0, 1), (0, 1))
。一般来说,如果您有一个列表
并且想要调用一个函数,
您可以使用
*
(解包)运算符将列表扩展为参数列表:The
product
function accepts an optionalrepeat
argument. The above is equivalent toitertools.product((0, 1), (0, 1), (0, 1), (0, 1))
.In general, if you have a list
and you'd like to call a function as
you could use the
*
(unpack) operator to expand the list into an argument list:如果您不使用
itertools.product
,您还可以使用*
运算符。*
运算符执行我认为您所说的“删除”的意思。它将列表或其他可迭代对象的内容转换为函数的位置参数。一般来说:在这个特定的示例中,代码将如下所示:
但是,在
itertools.product
的特定情况下,之前的答案(由 KennyTM 提供)可能更清晰:If you aren't using
itertools.product
, you could also use the*
operator. The*
operator does whatever I think you mean by "delist." It transforms the contents of a list or other iterable object into positional arguments for a function. In general:In this specific example, the code would look like this:
However, the previous answer (by KennyTM) is probably cleaner in the specific case of
itertools.product
: