1.List列表
①、列表遍历
charList = ['H','e','l','l','o']
extList = ['P','y','t','h','o','n']
# 列表遍历1
for value in charList:
print(value)
# 列表遍历2
for i in range(len(charList)):
print(i)
# 列表遍历,获取index和value(设置起始遍历索引)
for i,value in enumerate(charList,0):
print(i,value)
# 同时遍历两个列表
for value1,value2 in zip(charList,extList):
print(value1,value2)
# 反向遍历
for item in reversed(charList):
print(item)
②、列表排序
# 列表正序
charList.sort()
print(charList)
# 列表反序
charList.sort(reverse=True)
print(charList)
# 列表高级排序:对Item的某个关键字进行排序
L = [('A',1),('C',3),('B',2),('D',4)]
# L.sort(lambda x,y:cmp(x[1],y[1])) # Python 2.x
# lambda x:x[1] 是一个匿名函数,每次去取L中的元素x(元组),索引为1的值
L.sort(key=lambda x:x[1],reverse=True)
print(L)
# operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号)
import operator
L.sort(key=operator.itemgetter(1))
print(L)
# DSU排序方法:Decorate-Sort-Undercorate
config = [(x[1],i,x) for i,x in enumerate(L)]
config.sort()
print(L)
③、列表推导&切片
# 推导列表
print([[6 for x in range(5)] for y in range(3)])
# 切片:[start : end : step],step为步进值进行取值,step<0代表从右到左,step>0标识从左到右,结果返回List
# 反转List,与reverse()方法效果一致
print(charList[::-1])
# 反转字符串
print('Hello Python!'[::-1])
2.Dictionary字典
# 字典key遍历
for key in D:
print(key)
# 字典的遍历
for key,value in D.items():
print(key,value)
3.String字符串
# 字符串格式化一
a = "I'm %s. I'm %d year old" % ('CaiBird', 22)
# 字符串格式化二
b = '{0}llo Py{1}!!'.format('He','thon')
# 字符串格式化三
c = '{header}llo Py{footer}!!'.format(header='He',footer='thon')
# '!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用于在格式化某个值之前对其进行转化
import math
print('常量 PI 的值近似为: {}。'.format(math.pi))
#常量 PI 的值近似为: 3.141592653589793。
print('常量 PI 的值近似为: {!r}。'.format(math.pi))
#常量 PI 的值近似为: 3.141592653589793。