打印组合发生器时遇到问题

时间:2017-03-20 22:57:48

标签: python python-3.x

所以我正在探索itertools.combinations背后的代码。在文档中,它给出了“equivelent”如下:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

所以我想说我有一个清单:

sequence = [1,2,3,4,5,6,7,8,9,10] 

r=3

我试图将生成器转换为列表,然后打印它,但我得到了:

print(list(combinations(sequence,3)))
...
---> 16         indices[i] += 1
 17         for j in range(i+1, r):
 18             indices[j] = indices[j-1] + 1
TypeError: 'range' object does not support item assignment

我无法修改此功能而不会导致更多错误。 如果有人可以为我提供一些关于如何解决这个TypeError的指导,我会非常感激。

简而言之,我想知道为什么这样做有效但前面的代码没有:

print(list(itertools.combinations(sequence,3)))
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7) ...]

1 个答案:

答案 0 :(得分:0)

通过修改行:

<form action="#" method="POST" id="file-form" name="file-form" enctype="multipart/form-data">
    <div class="file-field input-field">
      <div class="btn">
        <span>File</span>
        <input type="file" class="upload" id="files" name="files" multiple>
      </div>
      <div class="file-path-wrapper">
        <input class="file-path validate" type="text" placeholder="Upload one or more files">
      </div>
    </div>

    <button class="btn waves-effect waves-light" type="submit" value="submit" name="action" onclick="submitForm()">Submit
        <i class="material-icons right">send</i>
    </button>
</form>

<script type="text/javascript">
function submitForm() {
   var resetForm = document.getElementsByName('file-form')[0];
   resetForm.submit(); 
   resetForm.reset(); 
   return false;
}
</script>

为:

indices = range(r)

回答了我的问题。谢谢你的评论。