[Python] python常用列表,数组操作范例 →→→→→进入此内容的聊天室

来自 , 2019-08-16, 写在 Python, 查看 120 次.
URL http://www.code666.cn/view/e345fac6
  1. # experimenting with Python's list
  2. # tested with Python23      vegaseat     21feb2005
  3. # import module os for method listdir()
  4. import os
  5. # creat an empty list (list object pointed to by iL)
  6. iL = []
  7. print "\nThese are the attributes and methods of a list:"
  8. print dir(iL)
  9. print "\nA list of America's Most Popular Lawyers:"
  10. print iL
  11. print "\nLoad the list with 0 to 9"
  12. for number in range(10):
  13.   iL.append(number)
  14. print "\nShow the loaded list:"
  15. print iL
  16. print "\nSame but simpler:"
  17. iL2 = range(10)
  18. print iL2
  19. print "\nThere are %d elements, min = %d, max = %d" % (len(iL), min(iL), max(iL))
  20. print "\nShow the first element (lists are zero based):"
  21. print iL[0]
  22. print "\nShow the final element:"
  23. print iL[-1]
  24. print "\nSum up all the integers in the list:"
  25. print sum(iL)
  26. # this is called slicing
  27. # [starting-at-index : but-less-than-index [ : step]]
  28. # start defaults to 0, end to len(sequence), step to 1
  29. print "\nShow the first 3 elements:"
  30. print iL[:3]
  31. print "\nShow every second element starting with index 1:"
  32. print iL[1::2]
  33. # cloning, assign one list to another list from start to end
  34. iL2 = iL[:]
  35. # aliasing is simpler, but iL3 retains the address of iL
  36. # so if you change iL you also change iL3, oops!!!
  37. iL3 = iL
  38. print "\nList assigned to another list:"
  39. print "original", iL, "id =", id(iL)
  40. print "clone   ", iL2, "id =", id(iL2)
  41. print "alias   ", iL3, "id =", id(iL3)
  42. # search the list for integer 7
  43. print "\nValue 7 is at index = %d\n" % iL.index(7)
  44. # insert an element
  45. print "Insert another 7 at that index:"
  46. iL.insert(iL.index(7),7)
  47. print iL
  48. print
  49. # check if there are two sevens
  50. if iL.count(7) == 2 :
  51.   print "There are two sevens in the list"
  52. elif iL.count(7) == 1 :
  53.   print "There is one seven in the list"
  54. else:
  55.   print "There are %d sevens in the list" % iL.count(7)
  56. print "\nRemove the extra 7 :"
  57. if iL.count(7) > 1 :
  58.   iL.remove(7)
  59. print iL
  60. print "\nReverse the list:"
  61. iL.reverse()
  62. print iL
  63. print "\nSort the list:"
  64. iL.sort()
  65. print iL
  66. # insert a list
  67. list1 = ['a', 'b', 'c', 'd', 'e']
  68. print "\nOriginal list:"
  69. print list1
  70. print "Insert another list at index 3:"
  71. list1.insert(3, ['n1', 'n2', 'n3'])
  72. print list1  # ['a', 'b', 'c', ['n1', 'n2', 'n3'], 'd', 'e']
  73. # using slicing to insert several elements into a list
  74. # this inserts elements of ['n1', 'n2', 'n3'] at index 3:
  75. list2 = ['a', 'b', 'c', 'd', 'e']
  76. print "\nInsert elements of another list at index 3:"
  77. list2[3:3] = ['n1', 'n2', 'n3']
  78. print list2  # ['a', 'b', 'c', 'n1', 'n2', 'n3', 'd', 'e']
  79. # using slicing to replace an element with other elements
  80. # this replaces element at index 3 with elements of ['n1', 'n2', 'n3']:
  81. list3 = ['a', 'b', 'c', 'd', 'e']
  82. print "\nReplace element at index 3 with elements of another list:"
  83. list3[3:4] = ['n1', 'n2', 'n3']
  84. print list3  # ['a', 'b', 'c', 'n1', 'n2', 'n3', 'e']
  85. # you can create a list of mixed types ...
  86. mixedList = []
  87. mixedList.append(1.23)
  88. mixedList.append('a')
  89. mixedList.append('mixed')
  90. mixedList.append('type')
  91. mixedList.append('list')
  92. mixedList.append(77777)
  93. mixedList.append(0xff)      # hex turns to decimal
  94. mixedList.append(355/113.0) # approximation of pi
  95. print "\nA list of mixed types:"
  96. print mixedList
  97. print
  98. # show the difference between two lists using zip() and list comprehension
  99. list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  100. list2 = [1, 2, 3, 4, 4, 6, 7, 8, 9, 11]
  101. print "list1 =", list1
  102. print "list2 =", list2
  103. print '-' * 60  # vanity line of dashes
  104. print "These are the items different in the two lists:"
  105. print [(x, y) for (x, y) in zip(list1, list2) if x != y]
  106. # let's go from integers to strings ...
  107. print "\nOriginal string:"
  108. s = "I'm dreaming of a white precipitate"
  109. print s
  110. # create a list of strings
  111. print "\nSeparate string at any whitespace to a list of words:"
  112. sL = []
  113. sL = s.split()
  114. print sL
  115. print "\nAdd 2 more words:"
  116. sL.append("in")
  117. sL.append("class")
  118. print sL
  119. # search the list for dreaming
  120. print "\n'dreaming' is at index = %d\n" % sL.index('dreaming')
  121. print "Insert an item at index 1 (moves rest of elements up):"
  122. sL.insert( 1, "merrily")
  123. print sL
  124. print "\nInsert an item one index in from the end:"
  125. sL.insert( -1, "chemistry")
  126. print sL
  127. print "\nPrint the list one item on a line:"
  128. # new line as delimiter
  129. print "\n".join(sL)
  130. print "\nJoin the list of words to form a string again:"
  131. # single space = " " as a delimiter
  132. s2 = " ".join(sL)
  133. print s2
  134. print "\nRemove 'white' from the list:"
  135. sL.remove('white')
  136. print sL
  137. # treat this list like a stack (last in first out)
  138. # like a stack of dinner plates
  139. print "\nOperate the present list like a stack (LIFO):"
  140. print "pop last element = " + sL.pop()
  141. print "pop second last  = " + sL.pop()
  142. print "pop third last  = " + sL.pop()
  143. print "this is left:"
  144. print sL
  145. print
  146. # treat this list like a queue (first in first out)
  147. # like the line at the store check-out
  148. print "Operate the present list like a queue (FIFO):"
  149. print "pop first element  = " + sL.pop(0)
  150. print "pop second element = " + sL.pop(0)
  151. print "this is left:"
  152. print sL
  153. print "\nSort this list:"
  154. sL.sort()
  155. print sL
  156. print "\nIs 'of' in this list?"
  157. if 'of' in sL:
  158.   print 'yes'
  159. # let's look at sorting a list of strings
  160. str = "I really love Monty Python's Flying Circus"
  161. wordList = []
  162. wordList = str.split()
  163. print "\nThe original list of words:"
  164. print wordList
  165. print "\nSort this list (the default sort is case sensitive):"
  166. wordList.sort()
  167. print wordList
  168. # use anonymous function lambda to do a case insensitive sort
  169. # in this example compare as all lower case strings
  170. # (somewhat inefficient but sweet for short lists)
  171. print "\nHere is a sort that is case insensitive:"
  172. import string
  173. wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y)))
  174. print wordList
  175. print
  176. # a way to weed out duplicate words from a list
  177. rawList = ['just', 'a', 'test', 'a', 'test', 'of', 'an', 'ordinary', 'string']
  178. # create an empty list
  179. uniqueList = []
  180. # use a list comprehension statement (takes a while to understand)
  181. [uniqueList.append(wrd) for wrd in rawList if not uniqueList.count(wrd)]
  182. print "The raw list containing duplicates:"
  183. print rawList
  184. print "The unique list (no duplicates):"
  185. print uniqueList
  186. # find all the .bmp files in the Windows folder
  187. print "\nAdd all the bitmap files in the Windows folder to a list:"
  188. path = 'c:/windows/'
  189. ext  = '.bmp'
  190. # create an empty list
  191. fileList = []
  192. for filename in os.listdir(path):
  193.   if filename.endswith(ext):
  194.     fileList.append(filename)
  195. # show the list of files
  196. print fileList
  197. print "\nShow one filename on each line:"
  198. for filename in fileList:
  199.   print filename
  200. #//python/5732

回复 "python常用列表,数组操作范例"

这儿你可以回复上面这条便签

captcha