Python List 笔记

Python List 笔记

in 表达式

>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True

+ * operator
+ 会导致生成一个新的 list, 在一个新的地址

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
>>> [0] * 4 
>[0, 0, 0, 0]

list slice
[:]复制 list 的好方法

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']

# So if you omit both, the slice is a copy of the whole list

>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

其他复制 list 的方法

c = list(a)   # pointer 指向一个新的地址

深层复制 deepcopy

以上所有copy的方法, + list(a) a[:], 如果 list 里包含其他 list, 则复制时依然保留了该 reference
   如果被包含的 list 内容发生了改变, 复制后的 list 内容也会发生改变
   如果想要在复制的同时去除这个 reference, 就需要使用深层复制

copy.deepcopy(x)

deepcopy 可能出现的问题:
   如果被复制的 list 里包含 recursive object, 则可能导致 infinite loop


append()
添加一个元素
还是原来的那个 object

>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']

+ operator
追加一个 list
创建一个新的 object

>>> t3 = t1 + [4]
>>> print t3
[1, 2, 3, 4]

extend()
添加一个 list

>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']

sort()

>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']

t.sort(reverse=True) # 从大到小排列 sort

sum()
把 List 里所有元素相加 (string无效)

>>> t = [1, 2, 3]
>>> sum(t)
6

pop()
无参数: 从 list 里去除最后一个元素, 并返回该元素
有参数: 从 list 里去除指定 index 的元素

>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b

del operator
删除 list 中的一个元素

>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']

范围性 del operator
end exclusive

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']

remove(‘x’)
如果 list 中有和参数一样的元素, 则把它删除
return None

>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']

list()
把 string 变成 list of characters

>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']

split()
无参数: 把一个带空格的 string 按照空格拆分为单词 list
有参数: 按照指定的 delimiter 把 string 拆分为 list

>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

join(’’)
使用 delimiter 把 list 串成一个 string
必须有参数, 也就是 delimiter

>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

map 和 lambda
依照给出的方法, 运算每一个 element, 然后生成一个新的 list
旧 list 不变

newList = map(lambda x : x^2, originalList)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值