列表和元组相关操作

  1.创建列表

n = list('hello')
print(n,type(n))

n = ['hello']
print(n,type(n))

>>>['h', 'e', 'l', 'l', 'o'] <class 'list'>
>>>['hello'] <class 'list'>

  2.元素赋值,使用索标记来为某个特定的,位置明确的元素赋值。

colour = ['white','red','black','blue','green']
colour[0] = 'yellow'
print(colour)
>>>['yellow', 'red', 'black', 'blue', 'green']

  3.删除元素

colour = ['white','red','black','blue','green']
del colour[2]
print(colour)
>>>['white', 'red', 'blue', 'green']

  4.分片赋值

  #如何一次性改变列表中多个元素

  5.append方法用于在列表末尾追加新的对象

colour = ['white','red','black','blue','green']
colour.append('yellow')
print(colour)
>>>['white', 'red', 'black', 'blue', 'green', 'yellow']

  它不是简单地返回一个修改过的新列表,而是直接修改原来的列表。  

  6.count方法统计个元素在列表中出现的次数。

n = ['to','be','do','in','be','not']
print(n.count('be'))
>>>2

x = [1,2,[1,2],2,[2,1,[1,2],3],2]
print(x.count(2))
print(x.count([1,2]))
>>>3
>>>1

  如果元素不存在列表中,则返回0

  7.extend方法可以在列表的末尾一次性追加另一个序列中的多个值。

a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
print(b)
>>>[1, 2, 3, 4, 5, 6]
>>>[4, 5, 6]

  看起来很像连接操作,两者最主要的区别在于:extend方法修改了被扩展的序列(即a),而原始的连接操作则不然,它会返回一个全新的列表。

a = [1,2,3]
b = [4,5,6]
x=a+b
print(x)
print(a)
print(b)

>>>[1, 2, 3, 4, 5, 6]
>>>[1, 2, 3]
>>>[4, 5, 6]
#或者a = a +b

  8.index方法用于从列表中找出某个值第一个匹配项的索引位置。

n = ['to','be','do','in','be','not']
print(n.index('to'))
>>>0

  #第二个怎么找?

  9.insert方法用于将对象插入到列表中。

num = [1,2,3,5,6,7]
num.insert(3,'four')
print(num)
>>>[1, 2, 3, 'four', 5, 6, 7]

  10.pop方法会移除列表中的一个元素(默认是最后一个),并返回该元素的值。

n = ['to','be','do','in','be','not','bee']
print(n.pop())
>>>bee

  pop方法是唯一一个既能修改列表又返回元素值(除了None)的列表方法。

  11.remove方法用于移除列表中某个值的第一个匹配项。

n = ['to','be','do','in','be','not','bee']
n.remove('be')
print(n)
>>>['to', 'do', 'in', 'be', 'not', 'bee']

  12.reverse方法将列表中的元素反向存放。

colour = ['white','red','black','blue','green']
colour.reverse()
print(colour)
>>>['green', 'blue', 'black', 'red', 'white']

  13.sort方法用于在原位置对列表进行排序(排序规则?),在‘原位置排序’意味着改变原来的列表,从而让其中的元素能按一定的顺序排列,而不是简单地返回一个已排序的列表副本。

x = [3,6,1,8,2,5,7,4]
x.sort()
print(x)
>>>[1, 2, 3, 4, 5, 6, 7, 8]

  当需要一个排好序的列表副本,同时又保留原有列表不变的时候。

x = [3,6,1,8,2,5,7,4]
y=x.sort()
print(x)
print(y)
>>>[1, 2, 3, 4, 5, 6, 7, 8]
>>>None

  需先把x的副本赋值给y,然后对y进行排序。

x = [3,6,1,8,2,5,7,4]
y=x[:] #得到包含了x所有元素的分片
y.sort()
print(x)
print(y)
>>>[3, 6, 1, 8, 2, 5, 7, 4]
>>>[1, 2, 3, 4, 5, 6, 7, 8]

  只是简单的把x赋值给y是没用的,这样做就让x和y都指向同一个列表了。

x = [3,6,1,8,2,5,7,4]
y=x
y.sort()
print(x)
print(y)
>>>[1, 2, 3, 4, 5, 6, 7, 8]
>>>[1, 2, 3, 4, 5, 6, 7, 8]

  


  元组即不可变列表

  元组除了创建和访问元组元素之外,没有太多其他操作。

猜你喜欢

转载自www.cnblogs.com/romacle/p/9877522.html