反復するとき、zipとizipの間に機能的な違いはありますか?

多分

私は以下のようなコードを持っています:

for v1, v2 in zip(iter1, iter2):
   print len(v1) # prints 0

しかし、zipをitertools.izipに変更すると、1が出力されます。

for v1, v2 in izip(iter1, iter2):
   print len(v1) # prints 1

他のすべてのコードは同じです。zipをizipに置き換えるだけで、機能しました。izipの出力は正しいものです。

編集:コード全体の追加:

#!/bin/python

"""
How to use:
>>> from color_assign import Bag, assign_colors
>>> from pprint import pprint
>>> old_topics = set([
... Bag(name='T1', group=0, color=1, count=16000),
... Bag(name='T2', group=0, color=1, count=16000),
... Bag(name='T3', group=1, color=2, count=16000),
... Bag(name='T4', group=2, color=3, count=16000),
... ])
>>> new_topics = set([
... Bag(name='T1', group=0, color=None, count=16000),
... Bag(name='T2', group=4, color=None, count=16000),
... Bag(name='T3', group=1, color=None, count=16000),
... Bag(name='T4', group=1, color=None, count=16000),
... ])
>>> color_ranges = [ [1,10] ]
>>> assign_colors(old_topics, new_topics, color_ranges)
>>> pprint(sorted(new_topics, key=attrgetter('name')))
[Bag(name=T1, group=0, color=1, count=16000),
 Bag(name=T2, group=4, color=3, count=16000),
 Bag(name=T3, group=1, color=2, count=16000),
 Bag(name=T4, group=1, color=2, count=16000)]
>>> 
"""

from itertools import groupby, izip
from operator import attrgetter

class Bag:
  def __init__(self, name, group, color=None, count=None):
    self.name  = name 
    self.group = group
    self.color    = color   
    self.count  = count 
  def __repr__(self):
    return "Bag(name={self.name}, group={self.group}, color={self.color}, count={self.count})".format(self=self)
  def __key(self):
    return self.name
  def __hash__(self):
    return hash(self.__key())
  def __eq__(self, other):
    return type(self) is type(other) and self.__key() == other.__key()

def color_range_gen(color_ranges, used_colors):
  color_ranges = sorted(color_ranges)
  color_iter = iter(sorted(used_colors))
  next_used = next(color_iter, None)
  for start_color, end_color in color_ranges:
    cur_color = start_color
    end_color = end_color
    while cur_color <= end_color:
      if cur_color == next_used:
        next_used = next(color_iter, None)
      else:
        yield cur_color
      cur_color = cur_color + 1


def assign_colors(old_topics, new_topics, color_ranges):
  old_topics -= (old_topics-new_topics) #Remove topics from old_topics which are no longer present in new_topics
  used_colors = set()

  def group_topics(topics):
    by_group = attrgetter('group')
    for _, tgrp in groupby(sorted(topics, key=by_group), by_group):
      yield tgrp

  for topic_group in group_topics(old_topics):
    oldtset = frozenset(topic_group)
    peek = next(iter(oldtset))
    try:
      new_group = next(topic.group for topic in new_topics if topic.name == peek.name and not topic.color)
    except StopIteration:
      continue
    newtset = frozenset(topic for topic in new_topics if topic.group == new_group)
    if oldtset <= newtset:
      for topic in newtset:
        topic.color = peek.color
      used_colors.add(peek.color)

  free_colors = color_range_gen(color_ranges, used_colors)
  unassigned_topics = (t for t in new_topics if not t.color)
  for tset, color in zip(group_topics(unassigned_topics), free_colors):
    for topic in tset:
      topic.color = color

if __name__ == '__main__':
  import doctest
  doctest.testmod()

使用法:

my_host:my_dir$ /tmp/color_assign.py
**********************************************************************
File "/tmp/color_assign.py", line 21, in __main__
Failed example:
    pprint(sorted(new_topics, key=attrgetter('name')))
Expected:
    [Bag(name=T1, group=0, color=1, count=16000),
     Bag(name=T2, group=4, color=3, count=16000),
     Bag(name=T3, group=1, color=2, count=16000),
     Bag(name=T4, group=1, color=2, count=16000)]
Got:
    [Bag(name=T1, group=0, color=None, count=16000),
     Bag(name=T2, group=4, color=3, count=16000),
     Bag(name=T3, group=1, color=2, count=16000),
     Bag(name=T4, group=1, color=2, count=16000)]
**********************************************************************
1 items had failures:
   1 of   7 in __main__
***Test Failed*** 1 failures.
my_host:my_dir$ sed -i 's/zip(/izip(/g' /tmp/color_assign.py
my_host:my_dir$ /tmp/color_assign.py
my_host:my_dir$

更新:問題は、groupbyzipを使用するときにイテレータ無効にすることです。

user2357112はモニカをサポートしています

あなたが経験している問題は、2つの要因の組み合わせによるものです。まず、izip必要に応じて基になるイテレータのみを進め、zipすべてのアイテムをすぐにフェッチする必要があります。次に、groupbyオブジェクトが進められると、以前のイテレータは無効になります

返されるグループは、それ自体が、基になるイテレータをと共有するイテレータですgroupby()ソースが共有されているため、groupby()オブジェクトが進められると、前のグループは表示されなくなります。したがって、そのデータが後で必要になった場合は、リストとして保存する必要があります。

簡単な修正として、グループを譲る前にそのグループgroup_topicsを呼び出すようlist変更できます。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

PublicAPIAttributeとUsedImplicitlyAttributeの間に機能的な違いはありますか?

分類Dev

-OutVariableと変数の割り当ての間に機能的な違いはありますか?

分類Dev

Rails 5では、「model.save」と「model.errors.empty」の間に機能的な違いはありますか?

分類Dev

F#のArray.replicateとArray.createの間に機能的な違いはありますか?

分類Dev

AtomicInteger.updateAndGet()とAtomicInteger.accumulateAndGet()の間に機能的な違いはありますか?

分類Dev

> *:first-childと>:first-childの間に機能的な違いはありますか?

分類Dev

[、] 2d配列と[] []配列の間に機能的な違いはありますか?

分類Dev

文字列での反復が機能するのに整数での反復が機能しない理由はありますか?

分類Dev

MinikubeとKindの間に大きな違いはありますか?

分類Dev

INTERSECTとINNERJOINの間に根本的な違いはありますか?

分類Dev

Rustの「(1..4)」と「{1..4}」の反復の間に異なるセマンティクスはありますか?

分類Dev

SetとArrayの間にCollectionスーパータイプはありますか?そうでない場合、関数はどのようにして集合と配列の両方で多型になることができますか(反復用)?

分類Dev

ifとif-elseの間にかなりの違いはありますか?

分類Dev

私が書いたJQueryコードが機能しなくなったのですが、見落としている間違いはありますか?

分類Dev

待機ありとなしの返品に違いはありますか

分類Dev

ListViewActivityを拡張することと、IDでリストビューを作成することとの間に大きな違いはありますか?

分類Dev

jsonを反復するときにFlatListが機能しない

分類Dev

`;`と `&&`と `|`の間に違いはありますか?

分類Dev

java:ResultSetの反復とリストの反復:パフォーマンスの違いはありますか

分類Dev

ネイティブjsdefaultValueとjQueryprop(defaultValue)の間に違いはありますか(あるべきですか)?

分類Dev

この使用例では、TCP_CORKとTCP_NODELAYの間に大きな違いはありますか?

分類Dev

Java ArrayDequeのpop()とremove()の間に重要な違いはありますか?

分類Dev

c#密封されたとJavaの最後のキーワードの間に機能的な違いはありますか?

分類Dev

Pythonの「string」と「string」の間に違いはありますか?

分類Dev

:=と[[の間に動作の違いはありますか?

分類Dev

データフレームの列の値を反復処理することと、列のデータに変数を割り当てることの間に違いはありますか?

分類Dev

CHAR_INTとINTの主キーの間に大きなクエリ速度の違いはありますか?

分類Dev

id()を使用する場合、[]とlist()の間に違いはありますか?

分類Dev

ScreenUpdatingとApplication.Visibleの間に視覚的な違いはありますか?

Related 関連記事

  1. 1

    PublicAPIAttributeとUsedImplicitlyAttributeの間に機能的な違いはありますか?

  2. 2

    -OutVariableと変数の割り当ての間に機能的な違いはありますか?

  3. 3

    Rails 5では、「model.save」と「model.errors.empty」の間に機能的な違いはありますか?

  4. 4

    F#のArray.replicateとArray.createの間に機能的な違いはありますか?

  5. 5

    AtomicInteger.updateAndGet()とAtomicInteger.accumulateAndGet()の間に機能的な違いはありますか?

  6. 6

    > *:first-childと>:first-childの間に機能的な違いはありますか?

  7. 7

    [、] 2d配列と[] []配列の間に機能的な違いはありますか?

  8. 8

    文字列での反復が機能するのに整数での反復が機能しない理由はありますか?

  9. 9

    MinikubeとKindの間に大きな違いはありますか?

  10. 10

    INTERSECTとINNERJOINの間に根本的な違いはありますか?

  11. 11

    Rustの「(1..4)」と「{1..4}」の反復の間に異なるセマンティクスはありますか?

  12. 12

    SetとArrayの間にCollectionスーパータイプはありますか?そうでない場合、関数はどのようにして集合と配列の両方で多型になることができますか(反復用)?

  13. 13

    ifとif-elseの間にかなりの違いはありますか?

  14. 14

    私が書いたJQueryコードが機能しなくなったのですが、見落としている間違いはありますか?

  15. 15

    待機ありとなしの返品に違いはありますか

  16. 16

    ListViewActivityを拡張することと、IDでリストビューを作成することとの間に大きな違いはありますか?

  17. 17

    jsonを反復するときにFlatListが機能しない

  18. 18

    `;`と `&&`と `|`の間に違いはありますか?

  19. 19

    java:ResultSetの反復とリストの反復:パフォーマンスの違いはありますか

  20. 20

    ネイティブjsdefaultValueとjQueryprop(defaultValue)の間に違いはありますか(あるべきですか)?

  21. 21

    この使用例では、TCP_CORKとTCP_NODELAYの間に大きな違いはありますか?

  22. 22

    Java ArrayDequeのpop()とremove()の間に重要な違いはありますか?

  23. 23

    c#密封されたとJavaの最後のキーワードの間に機能的な違いはありますか?

  24. 24

    Pythonの「string」と「string」の間に違いはありますか?

  25. 25

    :=と[[の間に動作の違いはありますか?

  26. 26

    データフレームの列の値を反復処理することと、列のデータに変数を割り当てることの間に違いはありますか?

  27. 27

    CHAR_INTとINTの主キーの間に大きなクエリ速度の違いはありますか?

  28. 28

    id()を使用する場合、[]とlist()の間に違いはありますか?

  29. 29

    ScreenUpdatingとApplication.Visibleの間に視覚的な違いはありますか?

ホットタグ

アーカイブ