标签: python-itertools

Pythonic在python 2.4中模拟itertools.product的方法

我有一个使用的python 3脚本itertools.product,但我需要能够在只安装了python 2.4的机器上运行它.由于itertools.product是python 2.6中的新功能,我无法再访问此功能.

如何itertools.product在Python 2.4中以pythonic方式模拟?

python python-2.4 python-itertools

3
推荐指数
2
解决办法
478
查看次数

itertools:排列的笛卡尔乘积

使用pythons itertools,我想在一堆列表的所有排列的外积上创建一个迭代器.一个明确的例子:

import itertools
A = [1,2,3]
B = [4,5]
C = [6,7]

for x in itertools.product(itertools.permutations(A),itertools.permutations(B),itertools.permutations(C)):
    print x
Run Code Online (Sandbox Code Playgroud)

虽然这有效,但我想将其推广到任意列表列表.我试过了:

for x in itertools.product(map(itertools.permutations,[A,B,C])):
    print x
Run Code Online (Sandbox Code Playgroud)

但它并没有按照我的意图行事.预期的产出是:

((1, 2, 3), (4, 5), (6, 7))
((1, 2, 3), (4, 5), (7, 6))
((1, 2, 3), (5, 4), (6, 7))
((1, 2, 3), (5, 4), (7, 6))
((1, 3, 2), (4, 5), (6, 7))
((1, 3, 2), (4, 5), (7, 6))
((1, 3, 2), (5, 4), (6, 7))
((1, 3, 2), …
Run Code Online (Sandbox Code Playgroud)

python permutation cartesian-product python-itertools

3
推荐指数
1
解决办法
1851
查看次数

迭代数组两次(笛卡尔积),但只考虑一半的元素

我试图迭代一个数组两次以拥有元素对(e_i,e_j),但我只想要i <j的元素.

基本上,我想要的就像是C语言.

int my_array[N] = ...;
for (int i=0; i<N; i++)
        for (int j=i+1; j<N; j++)
                something(my_array[i],my_array[j]);
Run Code Online (Sandbox Code Playgroud)

我没有找到我在itertools中寻找的东西(我发现的最接近的东西itertools.product(*iterables[, repeat])).

我尝试了一些事情,但我并不相信他们中的任何一个:

my_list=range(10)

# Using enumerate and slices - explicit loop
res=[]
for i,j in enumerate(my_list):
        for k in my_list[i+1:]:
                res.append((j,k))
print res

# Using enumerate and slices - list comprehension
res=[(j,k) for i,j in enumerate(my_list) for k in my_list[i+1:]]
print res

# Using enumerate and xrange - explicit loop
res=[]
for i,j in enumerate(my_list):
        for k …
Run Code Online (Sandbox Code Playgroud)

python combinations iterator python-itertools

3
推荐指数
1
解决办法
1475
查看次数

在列表中添加每个子列表的所有第二项

所以,我有一个包含许多子列表的列表,看起来像这样:

[[(1,2),1],[(5,2),3],[(4,0),2]]
Run Code Online (Sandbox Code Playgroud)

我想Python来加在一起的第二个项目中的每个列表,因此1,在3和2.我一直试图找到itertools它的功能,但我没有成功.

python list python-itertools

3
推荐指数
1
解决办法
1278
查看次数

string包含细长的单词

我的字符串是:"sooo dear how areeeee youuuuuu"

我想检查字符串中的单词是否拉长.

细长意味着:如果单词中的字符数重复超过两次,例如,也不会拉长,但是太长.

>>> import itertools
>>> my_str = 'soooo hiiiii whyyyy done'
>>> print [[g[0], sum(1 for _ in g[1])] for g in itertools.groupby(my_str)]
[['s', 1], ['o', 4], [' ', 1], ['h', 1], ['i', 5], [' ', 1], ['w', 1], ['h', 1], 
['y', 4], [' ', 1], ['d', 1], ['o', 1], ['n', 1], ['e', 1]]
Run Code Online (Sandbox Code Playgroud)

我想展示那个sooo,areeeee和youuuuuu是拉长的.我做了个别字符计数,但我想检查每个单词,看它是否拉长.

python string character python-itertools

3
推荐指数
1
解决办法
675
查看次数

我可以在python 2.4中使用什么而不是next()

我需要模拟izip_longest从itertools在Python 2.4

import itertools
class Tools:
    @staticmethod
    def izip_longest(*args, **kwds):
        # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
        fillvalue = kwds.get('fillvalue')
        counter = [len(args) - 1]
        def sentinel():
            if not counter[0]:
                raise ZipExhausted
            counter[0] -= 1
            yield fillvalue
        fillers = itertools.repeat(fillvalue)
        iterators = [itertools.chain(it, sentinel(), fillers) for it in args]
        try:
        while iterators:
            yield tuple(map(next, iterators))
        except ZipExhausted:
            pass       


class ZipExhausted(Exception):
    pass
Run Code Online (Sandbox Code Playgroud)

一切正常,直到我到达yield tuple(map(next, iterators)); Python 2.4抛出一个

NameError: global name 'next' is not …
Run Code Online (Sandbox Code Playgroud)

python python-2.4 next python-itertools

3
推荐指数
1
解决办法
774
查看次数

这个python代码可以更高效吗?

我编写了一些代码来查找字符串中有多少个子字符串是anagram对.要找到的函数anagram(anagramSolution)具有复杂度O(N).子串函数的复杂度小于N平方.但是,这里的代码就是问题所在.可以更优化吗?

for i in range(T):
    x = raw_input()
    alist = get_all_substrings(x)

    for k, j in itertools.combinations(alist,2):
        if(len(k) == len(j)):
            if(anagramSolution(k,j)):
                counter +=1

    counterlist.append(counter)
    counter = 0
Run Code Online (Sandbox Code Playgroud)

该alist可以有上千项(子集)的.主要问题是循环.迭代所有项目需要花费大量时间.有没有更快或更有效的方法来做到这一点?

python optimization for-loop time-complexity python-itertools

3
推荐指数
1
解决办法
133
查看次数

数组中的数字簇

我有一个像这样的数组:

A = [1,3,8,9,3,7,2,1,3,9,6,8,3,8,8,1,2]
Run Code Online (Sandbox Code Playgroud)

而且我想计算那些"入口集群"的数量>5.在这种情况下,结果应该是4,因为:

[1, 3, (8,9), 3, (7), 2, 1, 3, (9,6,8), 3, (8,8), 1, 2]
Run Code Online (Sandbox Code Playgroud)

给定L数组的长度,我可以这样做:

A = [1,3,8,9,3,7,2,1,3,9,6,8,3,8,8,1,2]
A = np.array(A)

for k in range(0,L):
    if A[k]>5:
        print k, A[k]
Run Code Online (Sandbox Code Playgroud)

这给了我所有大于的条目5.但是我怎么能对每一组数字进行分组呢?

python arrays cluster-computing python-itertools

3
推荐指数
1
解决办法
525
查看次数

当不需要通配符的某些特定组合时,如何在snakemake中使用expand?

假设我有以下文件,我想使用snakemake自动对其进行一些处理:

test_input_C_1.txt
test_input_B_2.txt
test_input_A_2.txt
test_input_A_1.txt
Run Code Online (Sandbox Code Playgroud)

以下snakefile用于expand确定所有可能的最终结果文件:

rule all:
    input: expand("test_output_{text}_{num}.txt", text=["A", "B", "C"], num=[1, 2])

rule make_output:
    input: "test_input_{text}_{num}.txt"
    output: "test_output_{text}_{num}.txt"
    shell:
        """
        md5sum {input} > {output}
        """
Run Code Online (Sandbox Code Playgroud)

执行上面的snakefile会导致以下错误:

test_input_C_1.txt
test_input_B_2.txt
test_input_A_2.txt
test_input_A_1.txt
Run Code Online (Sandbox Code Playgroud)

其中的原因错误是expand使用itertools.product引擎盖下产生的通配符的组合,其中一些发生在对应于丢失的文件。

如何过滤掉不想要的通配符组合?

python wildcard python-itertools higher-order-functions snakemake

3
推荐指数
1
解决办法
1057
查看次数

将Iterators链接到Flat Iterator

尝试使用itertools中的链来解决我的问题.我有一个迭代器列表,我想得到一个迭代器,以无缝方式迭代列表中的迭代器项.有办法吗?也许另一种工具而不是链条会更合适?

我的代码的简化示例:

iter1 = iter([1,2])
iter2 = iter([3,4])
iter_list = [iter1, iter2]
chained_iter = chain(iter_list)
Run Code Online (Sandbox Code Playgroud)

期望的结果:

chained_iter.next() --> 1
chained_iter.next() --> 2
chained_iter.next() --> 3
chained_iter.next() --> 4
Run Code Online (Sandbox Code Playgroud)

实际结果:

chained_iter.next() --> <listiterator at 0x10f374650>
Run Code Online (Sandbox Code Playgroud)

python iterator python-itertools python-2.7

3
推荐指数
1
解决办法
508
查看次数