一. List创建、索引、遍历和内置增删函数

  1.列表是Python的内置可变对象,由Array实现,支持任意类型的添加、组合和嵌套。

L = [] # list declare
L = [1, 1.024, 'dsp']
# List对象的引用的修改会造成原List的改变,需要copy()或者创建一个新的list对象(L[:])
title = L.copy() # shollow copy
title = M[:]
#索引 FROM 0 to len(L)-1,类似C语言数组。并支持反向索引 ->L[:-1] L[i:j]
print(L[::-1])
print( len(L), L[0:1], L[0:-1], L[0:] )

   2. 列表的插入增添元素操作: append()  insert() 数组移动导致开销过大,O(n)复杂度) extend(), 原地修改,不返回值

# Add element: 1.append 2.insert 3.extend
L.append('AI') # append object to end
L.append('CS') ex = ['python','C++','html']
L.extend(ex) # extend iterable object, L.extend("1")
L += ['php', 'go', 'java', 'javascript'] # 被解释器优化为extend()操作 L.insert(-1,'ML') # L.insert(index, object) -- insert object before index
L.insert(0,"football")
L.insert(len(l)-1,'real')

  3. 查找和删除操作: L.index()  L.count()  pop(index) remove() 

# search and find pos
L.index('python') # return first index of value
L.count('python') # return number of occurrences of value计数 # Delete elemnt: 1.pop 2.remove 3.del 4.clear # L.pop([index]) -> item: remove and return item at index (default last)
L.pop()
print(L.pop(0)) L_new = L.remove('dsp') # remove first occurrence of value移除第一个
print(L_new) del L[0:2]
L_new.clear() # L.clear() -> None -- remove all items
L print(L_new)

  4.排序: 列表解析和 sort、reverse 方法

L = [x for x in ('a', 'b', 'c', 'd', 'e')] 
alpha = list( map(ord , L) )
for i, a in zip(L, alpha):
  print( i, "ord", a) # 原处修改 L.sort() L.reverse()--> no return
# L.sort(key=None, reverse=False) -> None -- stable sort IN PLACE
L_new.sort() print("sort in palce", L_new)
L_new.sort(reverse=True)
print("reverse sort in place", L_new) print( sorted(L_new) ) # 返回一个新的对象
L_new.reverse() # L.reverse() -- reverse *IN PLACE*
print(L_new) M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # get column 2
col2 = [row[1] for row in M] title = L

二 . Dict创建、修改和内置增删函数

  1.字典类型由哈希表实现,具有快速查找的特点。字典的key值必须是不可变元素如字符、数字和元组对象,Python中可动态的增加字典元素。

  字典创建的几种方法:

#[1] 声明创建 dict
D0 = {"id":1, 'info': {'name':'David', 'age':20, 'sex':'M'}} #[2] 空字典不断添加键值
D1 = {}
D1['id'] = 2 # 通过键获取value
D1['info'] = {'name':'Mick', 'age':17, 'sex':'F'} D1['id'] = 5 # 复制修改value
print( D0.get("id", 0) ) # D.get(key, defautl)方式取值,避免无键异常
if 'info' in D3:
print('exist ', D3['info']) #[3] 元组键值对赋值创建
D2 = dict( [('id', 3), ('info', {'name':'Lucy', 'age':16, 'sex':'F'}) ]) #[4] 键必须是string, 形如 key=value pairs的参数
D3 = dict( age = 4, text = {'name':'David', 'socre':666 } ) #[5] values equal
D4 = dict.fromkeys(['a', 'b'], 0) # 创建字典:键不同,值相同 #[6] 字典生成式
alpha = { chr( i+ord('a') ):i+ord('a') for i in range(26) }

  或者通过两个Values和Keys列表输入内置zip函数,得到形如(key,value)的zip对象。

keys = [ 'a', 'b', 'c' ]
values = [ 5, 6, 7 ]
D = {}
for key, value in zip( keys, values):
D[key] = value
# 直接通过zip键值对赋值
D = dict( zip( keys, values) )

  2.  其他增删函数 update()  |  pop(key)

#  内置方法获取键keys()、值values()
print( list( D0.keys() ) )
print( list( D0.values() ))
print( list( D0.items() ))

D1.update(D0)
print( D2.pop('info') )

  3. 字典解析、遍历

D = dict( k:0 for k in ['a', 'b'] ) 

# zip-->together keys and values, it returns a key-vlaue pairs
print( zip( ['a', 'b', 'c'], [1, 2, 3] ) )
D = dict( zip(['a', 'b', 'c'], [1, 2, 3]) )
D = { k:v for k, v in zip(['a', 'b', 'c'], [1, 2, 3]) }
alpha = { i: chr( ord('a')+i-1 ) for i in range(1,27) }
# 迭代
ks = D.keys() # 为可迭代对象Iterable
ks.sort()
for k in ks:
print(k, '->', D[k])
for k in sorted( D.keys() ):
print(k, D[k]) # dictionary key exchange with value
def changedict(dic):
mydict = {}
for key in dic:
mydict.update({}.fromkeys(dic[key],key))
return mydict
# 键值交换
def revert_dict( d ):
   new_dict = { }
  for key in d.keys():
    new_dict[ d[key] ] = key
     return new_dict
print( revert_dict(alpha) )

# 参考《python 学习手册》

# 转载请注明来源:  https://www.cnblogs.com/justLittleStar/p/10417760.html

最新文章

  1. IOS开发基础知识--碎片29
  2. 使用Group By注意事项
  3. struts 2.3.14.1 包详解
  4. git命令笔记
  5. pom中定义某jar包的依赖,但并不使用该jar包,那最后部署的应用中会有这个jar包么?
  6. 二模10day2解题报告
  7. Douglas Crockford: entityify & deentityify
  8. spoj 2
  9. ListView的item中有button和checkbox,listview的点击事件无效
  10. VMware vSphere 服务器虚拟化之十六 桌面虚拟化之VMware Horizon View
  11. HTML5获取当前的经纬度坐标
  12. aforge 学习-命名空间中文理解
  13. 企微云CRM操作指南 – 道一云|企微
  14. RS485转USB插电脑上通讯不上
  15. Intellij idea常用快捷键和技巧
  16. Java8学习笔记(二)--三个预定义函数接口
  17. [LeetCode] 367. Valid Perfect Square_Easy tag:Math
  18. WPF datagrid 设置表头线与颜色、透明度
  19. C语言复习---迭代法,牛顿迭代法,二分法求根
  20. Hive Tunning(三) 最佳实践

热门文章

  1. 关于thrift的一些探索——thrift序列化技术
  2. JS 和 Jq 获取客户端各种屏幕宽度和高度
  3. c++ nested class 嵌套类。
  4. 不错的.net开源项目
  5. 记两个std接口equal_range,set_difference
  6. IntelliJ IDEA自动补全变量名称和属性名称的快捷键
  7. oracle数据库恢复归档脚本
  8. POJ 3264 Balanced Lineup 【ST表 静态RMQ】
  9. [19/03/27-星期三] 容器_Iterator(迭代器)之遍历容器元素(List/Set/Map)&Collections工具类
  10. Hibernate之CRUD实践