code_junkie

select single item from a collection : Python

Nov 13th, 2011
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. print one(name for name in ('bob','fred') if name=='bob')
  2.  
  3. def one(g):
  4. try:
  5. val = g.next()
  6. try:
  7. g.next()
  8. except StopIteration:
  9. return val
  10. else:
  11. raise Exception('Too many values')
  12. except StopIteration:
  13. raise Exception('No values')
  14.  
  15. >>> name, = (name for name in ('bob','fred') if name=='bob')
  16. >>> name
  17. 'bob'
  18.  
  19. >>> name, = (name for name in ('bob','bob') if name=='bob')
  20. Traceback (most recent call last):
  21. File "<stdin>", line 1, in <module>
  22. ValueError: too many values to unpack
  23.  
  24. >>> name, = (name for name in ('fred','joe') if name=='bob')
  25. Traceback (most recent call last):
  26. File "<stdin>", line 1, in <module>
  27. ValueError: need more than 0 values to unpack
  28.  
  29. def one( someGenerator ):
  30. if len(list(someGenerator)) != 1: raise Exception( "Not a Singleton" )
  31.  
  32. >>> i2=itertools.islice((name for name in ('bob','fred') if name=='bob'),0,1,1)
  33. >>> i2.next()
  34. 'bob'
  35. >>> i2.next()
  36. Traceback (most recent call last):
  37. File "<interactive input>", line 1, in <module>
  38. StopIteration
  39. >>>
  40.  
  41. print (name for name in ('bob', 'fred') if name == 'bob').next()
  42.  
  43. def one(iterable):
  44. it = iter(iterable)
  45. val = it.next()
  46. try:
  47. it.next()
  48. except StopIteration:
  49. return val
  50. else:
  51. raise Exception('More than one value')
  52.  
  53. def one(seq):
  54. counter = 0
  55. for elem in seq:
  56. result = elem
  57. counter += 1
  58. if counter > 1:
  59. break
  60. if counter == 0:
  61. raise Exception('No values')
  62. elif counter > 1:
  63. raise Exception('Too many values')
  64. return result
  65.  
  66. children = [name for name in ('bob','fred') if name=='bob']
  67. if len(children) == 0:
  68. raise Exception('No values')
  69. elif len(children) > 1:
  70. raise Exception('Too many values')
  71. else:
  72. child = children[0]
  73.  
  74. def one(items):
  75. count = 0
  76. value = None
  77.  
  78. for item in items:
  79. if count:
  80. raise Exception('Too many values')
  81.  
  82. count += 1
  83. value = item
  84.  
  85. if not count:
  86. raise Exception('No values')
  87.  
  88. return value
Add Comment
Please, Sign In to add comment