- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
Python 的 itertools.combinations() 创建的结果是数字的组合。例如:
a = [7, 5, 5, 4]
b = list(itertools.combinations(a, 2))
# b = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)]
但我还想获得组合的索引,例如:
index = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
我该怎么做?
最佳答案
你可以使用枚举:
>>> a = [7, 5, 5, 4]
>>> list(itertools.combinations(enumerate(a), 2))
[((0, 7), (1, 5)), ((0, 7), (2, 5)), ((0, 7), (3, 4)), ((1, 5), (2, 5)), ((1, 5), (3, 4)), ((2, 5), (3, 4))]
>>> b = list((i,j) for ((i,_),(j,_)) in itertools.combinations(enumerate(a), 2))
>>> b
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
关于Python itertools.combinations : how to obtain the indices of the combined numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27150990/
itertools.repeat(n) 和 itertools.cycle(n) 有区别吗?看起来,它们产生相同的输出。在我需要某个元素的无限循环的情况下,使用一种更有效吗? 最佳答案 简单地说,it
在编写一个查找列表中所有不同组合的程序时,我发现了很多关于使用 intertools.product() 而不是 intertools.combinations_with_replacement()
这段代码: from itertools import groupby, count L = [38, 98, 110, 111, 112, 120, 121, 898] groups = group
我正在读取一个文件(同时执行一些昂贵的逻辑),我需要在不同的函数中迭代多次,所以我真的只想读取和解析文件一次。 解析函数解析文件并返回一个itertools.groupby对象。 def parse_
下面是一些关于itertools.tee的测试: li = [x for x in range(10)] ite = iter(li) ========================
为什么下面的工作: from itertools import chain 但下面的不是吗? import itertools.chain as chain 最佳答案 import foo.bar 语
我必须在列表中生成所有 2 对项目组合。现在,我知道有两种方法可以实现此目的:嵌套 for 循环和 python 的内置 itertools: from itertools import combin
给定 r 为 4 的 itertools 组合: from itertools import combinations mylist = range(0,35) r = 4 combinationsl
我有一个列表 = [1, 2, 3, 3, 6, 8, 8, 10, 2, 5, 7, 7]我正在尝试使用 groupby 将其转换为 1 2 3 3 6 8,8 10 2, 5 7,7 基本上,任何
我正在使用itertools对字典键进行分组,使用以下内容: host_data = [] for k,v in itertools.groupby(temp_data, key=lambda x:x
我将自定义函数保存在一个单独的模块中,以便在需要时调用。我的一个新函数使用 itertools,但我不断收到名称错误。 NameError: name 'itertools' is not defin
我有一个简单的 python 函数来执行 itertools 乘积函数。如下所示。 def cart(n, seq): import itertools b = 8 while
我正在创建大量带有替换(乘积)的排列,它需要大量的计算时间。让我们使用像这样的简单函数: def permutations(li): return [p for p in itertools.
我编写了以下代码,使所有 20 个字符长的字符串都包含 A、T、G 和 C 的组合。 但是,我想避免连续出现 3 个以上的相同字符,因此我添加了一个 if 函数来检查这一点。问题是,这是在 itert
我想要一个函数来生成任意数量的数组的叉积。 # Code to generate cross product of 3 arrays M = [1, 1] N = [2, 3] K = [4, 5]
这个问题已经有答案了: Cartesian Product of Sets where No Elements are Identical under Permutations in Python (
我使用 for num in Combinations(nums[0], number): 返回列表中数字的所有组合,其中 num = len(nums[0])- 1.. 我想做的是作为单独的变量返回
我想将 itertools.count 元素作为列表索引传递,但会导致以下错误: TypeError: list indices must be integers or slices, not ite
有没有更好的方法来列出所有可能的组合,并用每个元素的最小和最大出现次数进行替换,而不是(1)使用itertools.combinations_with_replacement()列出所有可能的组合,而
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 6 年前。 Improve th
我是一名优秀的程序员,十分优秀!