Python学习10_OnlineResource_EXE12

本文深入讲解了Python中列表的基本操作及高级用法,包括赋值、追加、切片等功能,并通过实例演示了如何利用列表推导式、排序方法等技巧高效地处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.

  b = colors   ## Does not copy the list

 

The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).

FOR and IN

  squares = [1, 4, 9, 16]
  sum = 0
  for num in squares:
    sum += num
  print sum  ## 30

list = ['larry', 'curly', 'moe']
  if 'curly' in list:
    print 'yay'

 

Range

The range(n) function yields the numbers 0, 1, ... n-1, and range(a, b) returns a, a+1, ... b-1

List Methods

Here are some other common list methods.

  • list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
  • list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
  • list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
  • list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
  • list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)
  • list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.)
  • list.reverse() -- reverses the list in place (does not return it)
  • list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).

Notice that these are *methods* on a list object, while len() is a function that takes the list (or string or whatever) as an argument.

  list = ['larry', 'curly', 'moe']
  list.append('shemp')         ## append elem at end
  list.insert(0, 'xxx')        ## insert elem at index 0
  list.extend(['yyy', 'zzz'])  ## add list of elems at end
  print list  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
  print list.index('curly')    ## 2

  list.remove('curly')         ## search and remove that element
  list.pop(1)                  ## removes and returns 'larry'
  print list  ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']

Common error: note that the above methods do not *return* the modified list, they just modify the original list.

  list = [1, 2, 3]
  print list.append(4)   ## NO, does not work, append() returns None
  ## Correct pattern:
  list.append(4)
  print list  ## [1, 2, 3, 4]

List Build Up

One common pattern is to start a list a the empty list [], then use append() or extend() to add elements to it:

  list = []          ## Start as the empty list
  list.append('a')   ## Use append() to add elements
  list.append('b')

List Slices

Slices work on lists just as with strings, and can also be used to change sub-parts of the list.

  list = ['a', 'b', 'c', 'd']
  print list[1:-1]   ## ['b', 'c']
  list[0:2] = 'z'    ## replace ['a', 'b'] with ['z']
  print list         ## ['z', 'c', 'd']

List Comprehensions (optional)

List comprehensions are a more advanced feature which is nice for some cases but is not needed for the exercises and is not something you need to learn at first (i.e. you can skip this section). A list comprehension is a compact way to write an expression that expands to a whole list. Suppose we have a list nums [1, 2, 3, 4], here is the list comprehension to compute a list of their squares [1, 4, 9, 16]:

  nums = [1, 2, 3, 4]

  squares = [ n * n for n in nums ]   ## [1, 4, 9, 16]

The syntax is expr for var in list ] -- the for var in list looks like a regular for-loop, but without the colon (:). The expr to its left is evaluated once for each element to give the values for the new list. Here is an example with strings, where each string is changed to upper case with '!!!' appended:

  strs = ['hello', 'and', 'goodbye']

  shouting = [ s.upper() + '!!!' for s in strs ]
  ## ['HELLO!!!', 'AND!!!', 'GOODBYE!!!']

You can add an if test to the right of the for-loop to narrow the result. The if test is evaluated for each element, including only the elements where the test is true.

  ## Select values <= 2
  nums = [2, 8, 1, 6]
  small = [ n for n in nums if n <= 2 ]  ## [2, 1]

  ## Select fruits containing 'a', change to upper case
  fruits = ['apple', 'cherry', 'banana', 'lemon']
  afruits = [ s.upper() for s in fruits if 'a' in s ]
  ## ['APPLE', 'BANANA']

EXE1:

# A. match_ends

# Given a list of strings, return the count of the number of

# strings where the string length is 2 or more and the first

# and last chars of the string are the same.

# Note: python does not have a ++ operator, but += works.

def match_ends(words):

  sum = 0

  for ele in words:

    if len(ele) > 1 and ele[0] == ele[-1]:

      sum += 1

  return sum







# B. front_x

# Given a list of strings, return a list with the strings

# in sorted order, except group all the strings that begin with 'x' first.

# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields

# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

# Hint: this can be done by making 2 lists and sorting each of them

# before combining them.

def front_x(words):

  '''String 通过 内置函数 ord() 获得每个字符的 Unicode 编码进行大小比较'''

  i = 0

  l = []

  for ele in words:

    if ele[0] == 'x':

      l.append(ele)

      words.remove(ele)

  '''没有下面写得这种方式'''

  '''while i < len(words):

    while i < len(words) - 1:

      if words[i] > words[i + 1]:

        temp = words[i]

        words[i] = words[i + 1]

        words[i + 1] = temp

      i += 1 '''

  return sorted(l) + sorted(words)





# C. sort_last

# Given a list of non-empty tuples, return a list sorted in increasing

# order by the last element in each tuple.

# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields

# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]

# Hint: use a custom key= function to extract the last element form each tuple.

def sort_last(tuples):

  return sorted(tuples,key = lambda x:x[-1])







# Simple provided test() function used in main() to print

# what each function returns vs. what it's supposed to return.

def test(got, expected):

  if got == expected:

    prefix = ' OK '

  else:

    prefix = '  X '

  print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))





# Calls the above functions with interesting inputs.

def main():

  print('match_ends')

  test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)

  test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)

  test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)



  print

  print('front_x')

  test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),

       ['xaa', 'xzz', 'axx', 'bbb', 'ccc'])

  test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),

       ['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])

  test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),

       ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])



       

  print

  print('sort_last')

  test(sort_last([(1, 3), (3, 2), (2, 1)]),

       [(2, 1), (3, 2), (1, 3)])

  test(sort_last([(2, 3), (1, 2), (3, 1)]),

       [(3, 1), (1, 2), (2, 3)])

  test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),

       [(2, 2), (1, 3), (3, 4, 5), (1, 7)])





if __name__ == '__main__':

  main()

RE1:

 

EXE2:

Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.
  b = colors   ## Does not copy the list

The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).
FOR and IN
  squares = [1, 4, 9, 16]
  sum = 0
  for num in squares:
    sum += num
  print sum  ## 30
list = ['larry', 'curly', 'moe']
  if 'curly' in list:
    print 'yay'

Range
The range(n) function yields the numbers 0, 1, ... n-1, and range(a, b) returns a, a+1, ... b-1
List Methods
Here are some other common list methods.
list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.
list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().
list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)
list.sort()[sort()方法 对原列表进行修改。
list.sort(cmp=None, key=None, reverse=False)
cmp -- 可选参数, 如果指定了该参数会使用该参数的方法进行排序。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序, reverse = False 升序(默认)。
PS:key 和 reverse 比一个等价的 cmp 函数处理速度要快。这是因为对于每个列表元素,cmp 都会被调用多次,而 key和 reverse 只被调用一次
返回值
没有返回值,对原列表进行修改。
EXE1:
aList = [123, 'Google', 'Runoob', 'Taobao', 'Facebook'];
aList.sort();
print "List : ", aList
RE1:
List :  [123, 'Facebook', 'Google', 'Runoob', 'Taobao']
EXE2:
# 列表
vowels = ['e', 'a', 'u', 'o', 'i'] 
# 降序
vowels.sort(reverse=True)
# 输出结果
print '降序输出:', vowels
RE2:
降序输出: ['u', 'o', 'i', 'e', 'a']
EXE3:
# 获取列表的第二个元素
def takeSecond(elem):
    return elem[1] 
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)] 
# 指定第二个元素排序
random.sort(key=takeSecond)
# 输出类别
print '排序列表:', random
RE3:
排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]] -- sorts the list in place (does not return it). (The sorted()[sorted()方法 返回的是一个新的 list,而不是在原来的基础上进行的操作。
sorted(iterable[, cmp[, key[, reverse]]])
参数说明:
iterable -- 可迭代对象。
cmp -- 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
PS:key 和 reverse 比一个等价的 cmp 函数处理速度要快。这是因为对于每个列表元素,cmp 都会被调用多次,而 key和 reverse 只被调用一次
返回值
EXE1: L=[('b',2),('a',1),('c',3),('d',4)] 
 sorted(L, cmp=lambda x,y:cmp(x[1],y[1]))
 # 利用cmp函数(1.3版里面米有cmp函数,需要引入operate模块;2.3版里面也没有cmp这项参数;)
RE1:[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
EXE2:sorted(L, key=lambda x:x[1])
 # 利用key
RE2:[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
EXE3:students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted(students, key=lambda s: s[2])            
# 按年龄排序
RE3:[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
EXE4:sorted(students, key=lambda s: s[2], reverse=True)       
# 按降序
RE4:[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
] function shown later is preferred.)
list.reverse() -- reverses the list in place (does not return it)
list.pop(index) -- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append()).
Notice that these are *methods* on a list object, while len() is a function that takes the list (or string or whatever) as an argument.
  list = ['larry', 'curly', 'moe']
  list.append('shemp')         ## append elem at end
  list.insert(0, 'xxx')        ## insert elem at index 0
  list.extend(['yyy', 'zzz'])  ## add list of elems at end
  print list  ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
  print list.index('curly')    ## 2

  list.remove('curly')         ## search and remove that element
  list.pop(1)                  ## removes and returns 'larry'
  print list  ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']
Common error: note that the above methods do not *return* the modified list, they just modify the original list.
  list = [1, 2, 3]
  print list.append(4)   ## NO, does not work, append() returns None
  ## Correct pattern:
  list.append(4)
  print list  ## [1, 2, 3, 4]
List Build Up
One common pattern is to start a list a the empty list [], then use append() or extend() to add elements to it:
  list = []          ## Start as the empty list
  list.append('a')   ## Use append() to add elements
  list.append('b')
List Slices
Slices work on lists just as with strings, and can also be used to change sub-parts of the list.
  list = ['a', 'b', 'c', 'd']
  print list[1:-1]   ## ['b', 'c']
  list[0:2] = 'z'    ## replace ['a', 'b'] with ['z']
  print list         ## ['z', 'c', 'd']
EXE1:
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
  sum = 0
  for ele in words:
    if len(ele) > 1 and ele[0] == ele[-1]:
      sum += 1
  return sum



# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
  '''String 通过 内置函数 ord() 获得每个字符的 Unicode 编码进行大小比较'''
  i = 0
  l = []
  for ele in words:
    if ele[0] == 'x':
      l.append(ele)
      words.remove(ele)
  '''没有下面写得这种方式'''
  '''while i < len(words):
    while i < len(words) - 1:
      if words[i] > words[i + 1]:
        temp = words[i]
        words[i] = words[i + 1]
        words[i + 1] = temp
      i += 1 '''
  return sorted(l) + sorted(words)


# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
  return sorted(tuples,key = lambda x:x[-1])



# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))


# Calls the above functions with interesting inputs.
def main():
  print('match_ends')
  test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
  test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
  test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)

  print
  print('front_x')
  test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
       ['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
  test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
       ['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
  test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
       ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])

       
  print
  print('sort_last')
  test(sort_last([(1, 3), (3, 2), (2, 1)]),
       [(2, 1), (3, 2), (1, 3)])
  test(sort_last([(2, 3), (1, 2), (3, 1)]),
       [(3, 1), (1, 2), (2, 3)])
  test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
       [(2, 2), (1, 3), (3, 4, 5), (1, 7)])


if __name__ == '__main__':
  main()
RE1:

EXE2:
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
  l = []
  for num in nums:
    if nums.count(num) >=2:
      i = 0
      while i < nums.count(num): 
        nums.remove(num)
        i += 1
    l.append(num)
  return l


# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
  result =[]
  while len(list1) and len(list2):
    if list1[0] > list2[0]:
      result.append(list2.pop(0))
    else:
      result.append(list1.pop(0))
  if len(list1):
    result.extend(list1)
  if len(list2):
    result.extend(list2)
  return result

# Note: the solution above is kind of cute, but unforunately list.pop(0)
# is not constant time with the standard python list implementation, so
# the above is not strictly linear time.
# An alternate approach uses pop(-1) to remove the endmost elements
# from each list, building a solution list which is backwards.
# Then use reversed() to put the result back in the correct order. That
# solution works in linear time, but is more ugly.


# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))


# Calls the above functions with interesting inputs.
def main():
  print('remove_adjacent')
  test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
  test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
  test(remove_adjacent([]), [])

  print
  print('linear_merge')
  test(linear_merge(['aa', 'gg','xx', 'uu'], ['bb', 'cc','zz']),
       ['aa', 'bb', 'cc', 'gg','xx','uu','zz'])
  test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
       ['aa', 'bb', 'cc', 'xx', 'zz'])
  test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
       ['aa', 'aa', 'aa', 'bb', 'bb'])


if __name__ == '__main__':
  main()
RE2:

RE2:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值