list objects

今天来梳理一下Python list类型的知识点,特此申明下面信息均参考自公司培训课PPT Nagiza F. Samatova, NC State Univ. All rights,主要涉及到下面几个点:

  • Characteristics of the list objects
  • How to create a list?
  • List Comprehension
  • List Operations & Methods:access, update, delete
  • Memory Referencing and Garbage Collection
  • List Iterators
  • Copy
  • Performance
  • Exercise

Characteristics of the list objects

● List: a mutable sequence 可变有序

● Memory address (id()) does not change after changing the values 改变value内存地址不会改变

● Item values: no restrictions: heterogeneous-types, non-unique 没有限制,异类,不唯一

item value: none unique 不唯一

list_object = ['name', 'kelly', 'name', 'peter', 'name', 'Bob']
print(list_object)
# output:
['name', 'kelly', 'name', 'peter', 'name', 'Bob']

item value: heterogeneous 异类

# str, list, int
list_object1 = ['hello world', ['kelly', 'peter'], 2020]
# tuple, dict, function
list_object2 = [('kelly', 'peter'), {
    
    (17, 18, 19): 'age group'}, print]
print(list_object1)
print(list_object2)
# output: 
['hello world', ['kelly', 'peter'], 2020]
[('kelly', 'peter'), {
    
    (17, 18, 19): 'age group'}, <built-in function print>]

mutable: 可改变value, id不变,没有新对象生成,还是同一个对象

str_object = 'kelly'
list_object = list(str_object)
print('\t id: {}, \t list content: {}'.format(id(list_object), list_object))

def delete_first(list_arg):
    del list_arg[0]
    
delete_first(list_object)
print('\t id: {}, \t list content: {}'.format(id(list_object), list_object))

# output:
	 id: 2239125883072, 	 list content: ['k', 'e', 'l', 'l', 'y']
	 id: 2239125883072, 	 list content: ['e', 'l', 'l', 'y']

How to create a list?

● empty:

lst = list()
lst = []

● via coercion of another object: 强制类型转换

lst = list(another_object)
lst = [another_object]

tuple to list:

t = ('script', 'python')
lst_via_constructor = list(t)
lst_via_symbol = [t]
print('tuple to list via constructor:\nlist length:{}\tlist content:{} '.format(len(lst_via_constructor ), lst_via_constructor ))
print('tuple to list via symbol:\nlist length:{}\tlist content:{} '.format(len(lst_via_symbol), lst_via_symbol))

# output:
tuple to list via constructor:
list length:2	list content:['script', 'python'] 
tuple to list via symbol:
list length:1	list content:[('script', 'python')] 

dict to list

d = {
    
    'script': 'python'}
lst_via_constructor = list(d)
lst_via_symbol = [d]
print('dict to list via constructor:\nlist length:{}\tlist content:{} '.format(len(lst_via_constructor ), lst_via_constructor ))
print('dict to list via symbol:\nlist length:{}\tlist content:{} '.format(len(lst_via_symbol), lst_via_symbol))

# output:
dict to list via constructor:
list length:1	list content:['script'] 
dict to list via symbol:
list length:1	list content:[{
    
    'script': 'python'}] 

set to list

s = {
    
    'script', 'python'}
lst_via_constructor = list(s)
lst_via_symbol = [s]
print('set to list via constructor:\nlist length:{}\tlist content:{} '.format(len(lst_via_constructor ), lst_via_constructor ))
print('set to list via symbol:\nlist length:{}\tlist content:{} '.format(len(lst_via_symbol), lst_via_symbol))

# output:
set to list via constructor:
list length:2	list content:['python', 'script'] 
set to list via symbol:
list length:1	list content:[{
    
    'python', 'script'}] 

str to list

str_object = 'python'
lst_via_constructor = list(str_object)
lst_via_symbol = [str_object]
print('str to list via constructor:\nlist length:{}\tlist content:{} '.format(len(lst_via_constructor ), lst_via_constructor ))
print('str to list via symbol:\nlist length:{}\tlist content:{} '.format(len(lst_via_symbol), lst_via_symbol))

# output:
str to list via constructor:
list length:6	list content:['p', 'y', 't', 'h', 'o', 'n'] 
str to list via symbol:
list length:1	list content:['python'] 

List Comprehension – always returns list

# non pythonic way 
for item in list: 
    if conditional: 
        expression
# pythonic way 
[expression for item in list if conditional
new_list = [x.lower() for x in ['A', 'B', 'C', 'D']]
print(new_list)

# output:
['a', 'b', 'c', 'd']

List Operations & Methods

Access By-index

lst = [ 1, 2, 3 ] 
index = 2 
lst [ index ] = 5 
lst

# output:
[1, 2, 5]

Query: Using in operator: Membership Check
return Ture or False

info_list = ['kelly', 'peter']
is_kelly_in = 'kelly' in info_list
is_bob_in = 'Bob' in info_list
print('is kelly in info_list: {}'.format(is_kelly_in))
print('is bob in info_list: {}'.format(is_bob_in))

# output:
is kelly in info_list: True
is bob in info_list: False

List: Update Operations
Concatenation using ‘+’ operator
Concatenation using ‘ .extend()
Repetition using * operator:

group_a = ['Ann', 'Arthur']
group_b = ['Bob', 'Bred']
newGroup = group_a + group_b
group_a.extend(group_b)

print ('Concatenation using ‘+’ operator: {}'.format(newGroup))
print ('Concatenation using .extend(): {}'.format(group_a))
print ('Repetition using * operator: : {}'.format(group_b * 3))

# output:
Concatenation using + operator: ['Ann', 'Arthur', 'Bob', 'Bred']
Concatenation using .extend(): ['Ann', 'Arthur', 'Bob', 'Bred']
Repetition using * operator: : ['Bob', 'Bred', 'Bob', 'Bred', 'Bob', 'Bred']

List: insert(index, value) and append(value) methods

str_object = 'python'
list_object = list(str_object)
print('original list content: \n{}'.format(list_object))
list_object.insert(2, 'A')
print('list content after insert: \n{}'.format(list_object))
list_object.append('S')
print('list content after append: \n{}'.format(list_object))

insert是根据index进行插入
append总是list最后追加

# output:
original list content: 
['p', 'y', 't', 'h', 'o', 'n']
list content after insert: 
['p', 'y', 'A', 't', 'h', 'o', 'n']
list content after append: 
['p', 'y', 'A', 't', 'h', 'o', 'n', 'S']

List: Delete Operations
remove(value): 从list头部查找到value,删除一次
clear():清空list内容
pop([index]) :按index移除item,如果pop()则是移除list尾部最后一个item。

name_list = ['kelly', 'peter','peter', 'bob', 'bruce']
print('orignal list content:\n{}'.format(name_list))
name_list.remove('peter')
print('content after remove peter:\n{}'.format(name_list))
name_list.pop(1)
print('content after pop(1):\n{}'.format(name_list))
name_list.pop()
print('content after pop():\n{}'.format(name_list))
name_list.clear()
print('content after clear:\n{}'.format(name_list))
# output:
orignal list content:
['kelly', 'peter', 'peter', 'bob', 'bruce']
content after remove peter:
['kelly', 'peter', 'bob', 'bruce']
content after pop(1):
['kelly', 'bob', 'bruce']
content after pop():
['kelly', 'bob']
content after clear:
[]

Memory Referencing and Garbage Collection

下面几组例子对说初学者来说是容易出错的,对非基础类型的对象(如str, list。。。)赋值其实是将另一个对象的内存地址的引用赋值给该对对象,意味着该对象对另外一个对象拥有管理权。

a = [1,2,3]
b = a
a = [4,5,6]

print('a list content : {}'.format(a))
print('b list content : {}'.format(b))

1->a指向[1,2,3]的内存引用; 2-> a指向的引用赋值给b; 3-> a又指向新的内存引用[4,5,6],
b没有变化还是指向[1,2,3]

# output:
a list content : [4, 5, 6]
b list content : [1, 2, 3]
a = [1,2,3]
b = a
a.clear()
a = [4,5,6]

print('a list content : {}'.format(a))
print('b list content : {}'.format(b))

1->a指向[1,2,3]的内存引用; 2-> a指向的引用赋值给b; 3->将a指向的对象[1,2,3]清空; 4->a指向另外一个对象[4,5,6]
b还是指向原来[1,2,3]对象的引用,只是内容被清空了

a list content : [4, 5, 6]
b list content : []

有了前面的基础,下面这个应该很容易了吧,哈哈!

a = [1,2,3]
b = a
a = [4,5,6]
a.clear()

print('a list content : {}'.format(a))
print('b list content : {}'.format(b))
# output:
a list content : []
b list content : [1, 2, 3]

List Iterators

By-item

for item in list_obj:

By index-item pair

for index, item in enumerate(list_obj) :

By-index

for index in range(start_index, end_index, stride) :

name_str = 'one' 
list_obj = list (name_str)
for item in list_obj: 
    print ( item.upper())
print('Reversed: from end to start')           
for item in reversed(list_obj):
    print(item.upper())

Reversed: from end to start

# output:
O
N
E
Reversed: from end to start
E
N
O

Iterating Multiple Collections with zip()

name_list = ['kelly', 'peter']
city_list = ['Shanghai', 'Beijing']
for name, city in zip(name_list, city_list):
    print('{0} works in {1}'.format(name, city))
# output:
kelly works in Shanghai
peter works in Beijing

Iterating by Index, Item Pair using enumerate()

name_str = 'one' 
list_obj = list (name_str)

for index, item in enumerate(list_obj):
    list_obj[index] = item.upper()
    
print(list_obj)

# output:
['O', 'N', 'E']

Iterating by Index using range()

name_str = 'one' 
list_obj = list (name_str)

for index in range(0, len(list_obj)):
    list_obj[index] = list_obj[index].upper()
    
print(list_obj)

# output:
['O', 'N', 'E']

COPY

Makes a shallow copy
Memory address will be different

Slicing ( [ : ] )
Constructor( list() )

list_obj = [1,2,3]
list_copy = list_obj[:]
object_copy = list(list_obj)

print('original list:\nid:{}\tlist content:{}'.format(id(list_obj), list_obj))
print('list copy:\nid:{}\tlist content:{}'.format(id(list_copy), list_copy))
print('object copy:\nid:{}\tlist content:{}'.format(id(object_copy), object_copy))

内容是一样的,但是id不一样,是不同的对象

# output:
original list:
id:2239126915200	list content:[1, 2, 3]
list copy:
id:2239126870592	list content:[1, 2, 3]
object copy:
id:2239125951424	list content:[1, 2, 3]

Performance

Optimized to

● Store sets of heterogeneous information
● Appendnew items
● Update/replace list item at a specific index location
● Pop/deletethe most recent item
● Traversethe entire list or a subset/slice of the list

NOT Optimized to

● Inserta new item at a specific index position
● Pop/deletean item from arbitrary index position
● Check membership (with the in operator)
● Sort items of the list
● Copy list into a new list or create copy of the sorted list without changing the original list

Exercise

检验学习成果的时候到了,你能答对么在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/108992111