0

Python 2.5.5 を使用する Debian では、モジュールにクラスcollectionsがないことがわかりました。Iterable

例: http://python.codepad.org/PxLHuRFx

Python 2.5.6 を使用して OS X 10.8 で実行された同じコードが機能するため、何らかの理由でこれが欠落していると思います。

すべての Python 2.5+ でコードにこれを渡すには、どのような回避策が必要ですか?

4

2 に答える 2

4

__iter__オブジェクトに関数が定義されているかどうかを確認します。

それでhasattr(myObj, '__iter__')

于 2012-11-19T17:57:45.607 に答える
0

これは機能します:

def f(): pass
import sys  
results={'iterable':[],'not iterable':[]}

def isiterable(obj):
    try:
        it=iter(obj)
        return True
    except TypeError:
        return False


for el in ['abcd',[1,2,3],{'a':1,'b':2},(1,2,3),2,f,sys, lambda x: x,set([1,2]),True]:
    if isiterable(el):
        results['iterable'].append('\t{}, a Python {}\n'.format(el,type(el).__name__))
    else:   
        results['not iterable'].append('\t{}, a Python {}\n'.format(el,type(el).__name__))

print 'Interable:'
print ''.join(results['iterable'])

print 'Not Interable:'
print ''.join(results['not iterable'])

版画:

Interable:
    abcd, a Python str
    [1, 2, 3], a Python list
    {'a': 1, 'b': 2}, a Python dict
    (1, 2, 3), a Python tuple
    set([1, 2]), a Python set

Not Interable:
    2, a Python int
    <function f at 0x100492d70>, a Python function
    <module 'sys' (built-in)>, a Python module
    <function <lambda> at 0x100492b90>, a Python function
    True, a Python bool

これについては、この SO 投稿で詳しく説明しています。

于 2012-11-20T17:06:37.410 に答える