Guest User

Python Day #2

a guest
Sep 10th, 2014
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. a = [2,10,4,3,7]
  2. a.sort()
  3. print(a)
  4.  
  5. # returns a new sorted list without modifying source list
  6. a = [2,10,4,3,7]
  7. print(sorted(a))
  8. print(a)
  9.  
  10. # sort method with different type of objects
  11. a = ["hello", 1, "world", 45, 2]
  12. # a.sort() comparing int 2 str s not allowed in Python 3.x
  13. print(a)
  14.  
  15. # function as a sort key
  16. a = [[2,3], [4,6], [6,1]]
  17. a.sort(key=lambda x: x[1])
  18. print(a)
  19.  
  20. a = ['python', 'perl', 'java', 'c', 'haskell', 'ruby']
  21.  
  22. # sorts a list of strings based on length
  23. def lensort(a):
  24.     a.sort(key=len)
  25.     print(a)
  26.  
  27. lensort(a)
  28.  
  29. a = ['python', 'java', 'Python', 'Java']
  30.  
  31. # sorts a list of unique string
  32. def unique(a):
  33.     u = list(set(word.lower() for word in a))
  34.     u.sort()
  35.     print(u)
  36.  
  37. unique(a)
  38.  
  39. # tuples
  40. a = (1,2,3)
  41. print(a[0])
  42.  
  43. a = 1,2,3
  44. print(a[1])
  45.  
  46. print(len(a))
  47. print(a[0:])
  48. print(a[1:])
  49.  
  50. # sets
  51. x = set([3,1,2,1])
  52. print(x)
  53.  
  54. # other way of writing sets
  55. x = {3,2,1,3} # no need to use set word
  56. print(x)
  57.  
  58. # add elements to a set using add method
  59. x = set([1,2,3])
  60. x.add(4)
  61. print(x)
  62.  
  63. # existence of an element using in operator
  64. x = set([1,2,3])
  65. print(1 in x)
  66. print(5 in x)
  67.  
  68. # strings
  69. print(len("abrakadabra"))
  70.  
  71. a = "hello world"
  72. print(a[-4])
  73. print(a[::-1])
  74.  
  75. print(a.split()) # creating a list
  76.  
  77. b = "a,b,c"
  78. print(b.split(',')) # like above
  79.  
  80. c = "hello"
  81. d = "world"
  82. print(" ".join([c,d])) # join strings
  83.  
  84. print(b.strip(' world')) # strip letter
  85.  
  86. # formating values into strings
  87. print("%s %s" % (c,d))
  88. print('Cahpter %d: %s' % (3, 'Data Structures'))
  89.  
  90. # sorting by extension
  91. a = ['a.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt', 'x.c']
  92.  
  93. import os.path
  94.  
  95. def extsort(a):
  96.     a.sort(key=lambda f: os.path.splitext(f))
  97.     print(a)
  98.  
  99. extsort(a)
Advertisement
Add Comment
Please, Sign In to add comment