Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.12 KB | None | 0 0
  1. ## Get Number of unique elements in a list
  2. x = ['f', 'e', 'e', 'f', 'f']
  3.  
  4. # output: {'e': 2, 'f': 3}
  5. # Solution
  6. o = {i:x.count(i) for i in x}
  7. print(o)
  8.  
  9. #-----------------------------------------------------------------------------------------------------
  10. ## Get Number of unique elements in dict
  11. y = {'a': 1, 'c': 5, 'b': 4, 'd': 6, 'e':5, 'f':4, 'g':1, 'h':5}
  12. # output {1: 2, 4: 2, 5: 3, 6: 1}
  13.  
  14. # Solution
  15. o = {i:y.values().count(i) for i in y.values()}
  16. print(o)
  17.  
  18. #-----------------------------------------------------------------------------------------------------
  19. ## Get Number of unique values in a dict
  20. y = {'a': 1, 'c': 5, 'b': 4, 'd': 6, 'e':5, 'f':4, 'g':1, 'h':5}
  21. # output: [1, 4, 5, 6]
  22.  
  23. # Solution
  24. list(set(y.values()))
  25.  
  26. #-----------------------------------------------------------------------------------------------------
  27. ## Replace an existing item value with a new key in a dictionary
  28. y = {'a': 1, 'c': 5, 'b': 4}
  29. # output: {'c': 5, 'b': 4, 'anc': 1}
  30.  
  31. # Solution
  32. y['anc'] = y.pop('a')
  33.  
  34. #-----------------------------------------------------------------------------------------------------
  35. ## csv file with first row has column name, other rows contain data for each column. generate array of dict and JSON
  36. '''
  37. Eg.
  38. name, city,age, country , language ,phone
  39. abc,xyz, 23 , sdf, sdf, 3454
  40. dg, reer,43, dfgf , were,3454
  41. sdf, rtert , 26, sdfdf, fgf,43454
  42. '''
  43.  
  44. inf = open('csv2json.csv', 'r')
  45. lines = inf.readlines()
  46. cols = [x.strip() for x in lines.pop(0).strip().split(',')]
  47. out = [{j:d.strip().split(',')[i] for i,j in enumerate(cols)} for d in lines]
  48. print(out)
  49. ## [{'city': 'xyz', 'name': 'abc', 'language': ' sdf', 'country': ' sdf', 'age': ' 23 ', 'phone': ' 3454'}, {'city': ' reer', 'name': 'dg', 'language': ' were', 'country': ' dfgf ', 'age': '43', 'phone': '3454'}, {'city': ' rtert ', 'name': 'sdf', 'language': ' fgf', 'country': ' sdfdf', 'age': ' 26', 'phone': '43454'}]
  50.  
  51. import json
  52. json.dumps(out)
  53. ## '[{"city": "xyz", "name": "abc", "language": " sdf", "country": " sdf", "age": " 23 ", "phone": " 3454"}, {"city": " reer", "name": "dg", "language": " were", "country": " dfgf ", "age": "43", "phone": "3454"}, {"city": " rtert ", "name": "sdf", "language": " fgf", "country": " sdfdf", "age": " 26", "phone": "43454"}]'
  54.  
  55. #-----------------------------------------------------------------------------------------------------
  56. ## give example for pass by value, and pass by reference
  57. # all primitive datatypes arguments are 'passed by value'
  58. # others (list, dict, ...) are 'passed by reference'
  59.  
  60. #-----------------------------------------------------------------------------------------------------
  61. ## what is the use of r prefix?
  62. # remove tab (\\t)
  63. x = 'abc\\tsdkfk\\ndkfjk'
  64. re.sub(r'\\t', '', abc)
  65. # output: 'abcsdkfk\\ndkfjk'
  66.  
  67. # re.sub('\\t', '', abc) - Fail
  68. # re.sub('\t', '', abc) - Fail
  69.  
  70. #-----------------------------------------------------------------------------------------------------
  71. # Merge two dict uniq values
  72. x = {'a':1, 'b':2}
  73. y = {'e':3, 'y':2}
  74. # output: {'a': 1, 'y': 2, 'b': 2, 'e': 3}
  75. x.update(y)
  76.  
  77. {**x,**y}
  78. # {'a': 1, 'y': 2, 'b': 2, 'e': 3}
  79. {**y,**x}
  80. #{'b': 2, 'y': 2, 'e': 3, 'a': 1}
  81.  
  82. # Merge two dict with same key
  83. x = {'a':1, 'b':2}
  84. y = {'b':7, 'y':8}
  85. #{'a': 1, 'y': 8, 'b': 7}
  86. #{'a': 1, 'y': 8, 'b': 7}
  87.  
  88.  
  89. # Merge & Update Value in Dict
  90. x = {'a':1, 'b':2}
  91. c = ['b','c','d']
  92. v = [4,5,6]
  93. # output: {'a': 1, 'c': 5, 'b': 4, 'd': 6}
  94. x.update({a:v[i] for i, a in enumerate(c)})
  95.  
  96. #-----------------------------------------------------------------------------------------------------
  97. # sort list / dates:
  98. arr = ['05', '15', '01', '27', '07', '16', '03', '25', '08', '21', '30', '17', '04']
  99. #output = ['01', '03', '04', '05', '07', '08', '15', '16', '17', '21', '25', '27', '30']
  100.  
  101. def sortDates(inArr):
  102. lyStrip = lambda a: int(str(a).lstrip("0"))
  103. lyAdd = lambda w: '0'+str(w) if len(str(w)) == 1 else str(w)
  104. sortedArr = map(lyAdd, sorted(map(lyStrip,inArr)))
  105. return sortedArr
  106.  
  107. #arr = ['05', '15', '01', '27', '07', '16', '03', '25', '08', '21', '30', '17', '04']
  108. sarr = sortDates(arr)
  109. print(list(sarr))
  110.  
  111. #-----------------------------------------------------------------------------------------------------
  112. ## Remove an element from the list
  113. x = [3,4,2,5,6,1]
  114. #output: [3,2,5,6,1]
  115. x.remove(4)
  116.  
  117. ## remove an element by index
  118. x = [3,4,7,5,6,1]
  119. x.pop(2)
  120. x # output: [3,4,5,6,1] ## 7
  121. x.pop() # default remove the last element [3,4,5,6]
  122.  
  123. ## add/append an element to the list
  124. x.append(6)
  125.  
  126. ## get the index of an element
  127. x.index(6) ## 3
  128.  
  129. # add an element by index
  130. x[10] = 82 ## error: list index out of range
  131. x[3] = 82
  132. x ## [3, 4, 5, 82, 6]
  133.  
  134.  
  135. #-----------------------------------------------------------------------------------------------------
  136. # remove an item from the dict
  137. y = {'a': 1, 'c': 5, 'b': 4, 'd': 6}
  138. y.pop('a') ## {'c': 5, 'd': 6, 'b': 4}
  139. del y['a'] ## {'c': 5, 'b': 4}
  140.  
  141. # get the key of a given value (eg. 4) from the dictionary
  142. y = {'a': 1, 'c': 5, 'b': 4, 'd': 6,'e':4}
  143.  
  144. search_age = 4
  145. for name, age in y.items():
  146. if age == search_age:
  147. print(name)
  148. # output:'b' ,'e'
  149.  
  150. # replace lowercase keys to uppercase
  151. y = {'a': 1, 'c': 5, 'b': 4}
  152. {k.upper():y[k] for k in y} # output: {'A': 1, 'C': 5, 'B': 4} ## solution 1
  153. for k in y:
  154. print({k.upper():y[k]}) ## solution 2
  155. {k.upper():v for k,v in y.items()} ## solution 3
  156.  
  157. # change camelCase to snake_case of keys in dict
  158. d = {'aBc':1, 'cDe': 4, 'eFg': 5}
  159. lda = lambda x: '_' + x.group(1).lower()
  160. {re.sub('([A-Z])', lda, k) : d[k] for k in d}
  161. # output: {'e_fg': 5, 'c_de': 4, 'a_bc': 1}
  162.  
  163. # duplicate uppercase in keys in dict
  164. d = {'aBc':1, 'cDe': 4, 'eFg': 5}
  165. lda = lambda x: x.group(1)*2
  166. {re.sub('([A-Z])', lda, k) : d[k] for k in d}
  167. # output: {'cDDe': 4, 'eFFg': 5, 'aBBc': 1}
  168.  
  169.  
  170. # replace 0 in the list to 'null'
  171. x = [0,3,4,0,2,6,0]
  172. ["null" if a == 0 else a for a in x] ## solution 1
  173. map(lambda a: "null" if a == 0 else a, x) ## solution 2
  174. ## output ['null', 3, 4, 'null', 2, 6, 'null']
  175.  
  176. # remove spl characters from a string
  177. ab = 'sdfjkh@ghjg#$sdjfkl&hjh*kkj^kkj!@~kjkd<kjk,KJ;:lk '
  178. re.sub('[^\w]', '' ,ab) ## output: 'sdfjkhghjgsdjfklhjhkkjkkjkjkdkjkKJlk'
  179.  
  180. # excape all spl characters
  181. ab = 'sdfjkh@ghjg#$sdjfkl&hjh*kkj^kkj!@~kjkd<kjk,KJ;:lk'
  182. re.excape(ab) ## output: 'sdfjkh\\@ghjg\\#\\$sdjfkl\\&hjh\\*kkj\\^kkj\\!\\@\\~kjkd\\<kjk\\,KJ\\;\\:lk'
  183.  
  184. # remove all white space from a string
  185. x = 'abc\t hdnf sdf\ndslfk\n\tddff'
  186. re.sub('\s+', '', x) ## output: 'abchdnfsdfdslfkddff'
  187.  
  188. # replace a string from an input string -> to be case insensitive
  189. x = 'cancer and Tumor are the same'
  190. re.sub('tumor|cancer', '', v, flags=re.IGNORECASE) ##output: ' and are the same'
  191.  
  192. # replace if 'tumor', or 'cancer' present in the string elements in the list
  193. x = ['lung Cancer', 'brain tumor', 'kidney tumor', 'lung Tumor', 'blood cancer']
  194. map(lambda y: re.sub(' cancer| tumor', '', y, flags=re.IGNORECASE), x) #output: ['lung', 'brain', 'kidney', 'lung', 'blood']
  195.  
  196. # convert all elements to string
  197. n = [['a', 1], ['b', 2], ['c', 3]]
  198. [[str(j) for j in i] for i in n] ## solution 1
  199. map(lambda i: map(lambda j: str(j), i), n) ## solution 2
  200. ## output: [['a', '1'], ['b', '2'], ['c', '3']]
  201.  
  202. # can we merge list, tuple, and set?
  203. a = [1,2,3]
  204. b = (4,5,6)
  205. c = set([6,7,8])
  206. a.extend(b)
  207. a.extend(c)
  208. ## output: [1, 2, 3, 4, 5, 6, 8, 6, 7]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement