do_iter.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from collections.abc import Iterable, Iterator
  4. def g():
  5. yield 1
  6. yield 2
  7. yield 3
  8. print('Iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable))
  9. print('Iterable? \'abc\':', isinstance('abc', Iterable))
  10. print('Iterable? 123:', isinstance(123, Iterable))
  11. print('Iterable? g():', isinstance(g(), Iterable))
  12. print('Iterator? [1, 2, 3]:', isinstance([1, 2, 3], Iterator))
  13. print('Iterator? iter([1, 2, 3]):', isinstance(iter([1, 2, 3]), Iterator))
  14. print('Iterator? \'abc\':', isinstance('abc', Iterator))
  15. print('Iterator? 123:', isinstance(123, Iterator))
  16. print('Iterator? g():', isinstance(g(), Iterator))
  17. # iter list:
  18. print('for x in [1, 2, 3, 4, 5]:')
  19. for x in [1, 2, 3, 4, 5]:
  20. print(x)
  21. print('for x in iter([1, 2, 3, 4, 5]):')
  22. for x in iter([1, 2, 3, 4, 5]):
  23. print(x)
  24. print('next():')
  25. it = iter([1, 2, 3, 4, 5])
  26. print(next(it))
  27. print(next(it))
  28. print(next(it))
  29. print(next(it))
  30. print(next(it))
  31. d = {'a': 1, 'b': 2, 'c': 3}
  32. # iter each key:
  33. print('iter key:', d)
  34. for k in d.keys():
  35. print('key:', k)
  36. # iter each value:
  37. print('iter value:', d)
  38. for v in d.values():
  39. print('value:', v)
  40. # iter both key and value:
  41. print('iter item:', d)
  42. for k, v in d.items():
  43. print('item:', k, v)
  44. # iter list with index:
  45. print('iter enumerate([\'A\', \'B\', \'C\']')
  46. for i, value in enumerate(['A', 'B', 'C']):
  47. print(i, value)
  48. # iter complex list:
  49. print('iter [(1, 1), (2, 4), (3, 9)]:')
  50. for x, y in [(1, 1), (2, 4), (3, 9)]:
  51. print(x, y)