Python数据操作

1 切片操作

从序列中取出一部分元素,主要用于 List、Tuple、Str

L[0:3]  #从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。
L[:3]  #如果第一个索引是0,还可以省略 取前三个
L[1:3]  # 以从索引1开始,取出2个元素出来
L[2:] #从索引2开始一直到最后
L[-1] #倒数第一个元素
L[-2] #倒数第二个元素
L[-2:] #从倒数第二个开始一直到最后 后两个数
L[-3:-1] #从倒数第三个到最后
L[:10:2]  # 前10个数,每两个取一个
L[::5] #所有数,每5个取一个
L[:]  #什么都不写,只写[:]就可以原样复制一个list

2 字符串操作

2.1 字符串操作方法

  • strip,lstrip,rstrip 去除空格或指定字符

  • lower,upper 大小写

  • startswith,endswith 判断是否以指定字符串结束/开始

  • format的三种用法

    res='{} {} {}'.format('egon',18,'male')
    res='{1} {0} {1}'.format('egon',18,'male')
    res='{name} {age} {sex}'.format(sex='male',name='alan',age=18)
    
  • split,rsplit

    name='root:x:0:0::/root:/bin/bash'
    print(name.split(':')) #默认分隔符为空格
    name='C:/a/b/c/d.txt' #只想拿到顶级目录
    print(name.split('/',1))
    
    name='a|b|c'
    print(name.rsplit('|',1)) #从右开始切分
    
  • join

    tag=' '
    print(tag.join(['alan','say','hello','world'])) #可迭代对象必须都是字符串
    
  • replace

    name='alex say :i have one tesla,my name is alex'
    print(name.replace('alex','SB',1))
    
  • isdigit 判断字符串是否只包含字符串

  • find,rfind 返回某字符字符串中第一次出现/最后一次出现 的索引,没有 -1 可以指定范围

  • index,rindex 同上,不存在保持

  • count 返回某个字符串出现的次数 可以指定范围

  • captalize, swapcase, title 首字母大写/大小写翻转/每个单词首字母大写

2.2 字符串练习

# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " danedanA"
# 1)    移除 name 变量对应的值两边的空格,并输出处理结果
# 2)    判断 name 变量对应的值是否以 "da" 开头,并输出结果
# 3)    判断 name 变量对应的值是否以 "A" 结尾,并输出结果
# 4)    将 name 变量对应的值中的 “d” 替换为 “p”,并输出结果
# 5)    将 name 变量对应的值根据 “d” 分割,并输出结果。
# 6)    将 name 变量对应的值变大写,并输出结果
# 7)    将 name 变量对应的值变小写,并输出结果
# 8)    请输出 name 变量对应的值的第 2 个字符
# 9)    请输出 name 变量对应的值的前 3 个字符
# 10)    请输出 name 变量对应的值的后 2 个字符?
# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?
# 12)    获取子序列,去掉最后一个字符。如: dandan 则获取 danda。

3 集合关系运算

3.1 集合运算

  • | 合集
  • & 交集
  • - 差集
  • ^ 对称差集
  • 父集:>,>=
  • 子集:<,<=
# 有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
pythons={'alex','alan','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
# 求出即报名python又报名linux课程的学员名字集合
print(pythons & linuxs)
# 求出所有报名的学生名字集合
print(pythons | linuxs)
# 求出只报名python课程的学员名字
print(pythons - linuxs)
# 求出没有同时这两门课程的学员名字集合
print(pythons ^ linuxs)

3.2 集合操作方法

  • set.add(obj) 集合中添加一个元素
  • set.update(set) 添加多个
  • set.remove(obj) 删除集合成员

4 列表操作

4.1 列表生成器

[i for i in range(1,11)]  #1到10组成的列表
[i for i in range(1,11) if i % 2 == 0] #1到10中间的偶数组成的列表
[i * i for i in range(1,11)] #1到10 每个数的平方 组成的列表
[2 ** i for i in range(0,11)] #2的0次方 到 10次方

4.2 列表操作符

  • + 组合列表
  • * 重复列表
  • 元祖也支持以上运算符

4.3 删除列表中元素

  • del list[index]
  • list.pop([index]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
  • list.remove(obj) 移除列表中某个值的第一个匹配项

4.4 列表中添加元素

  • list.append(obj) 在列表末尾添加新的元素
  • list.insert(index, obj) 指定位置插入元素

4.5 其他列表操作

  • list.count(obj) 统计某个元素在列表中出现的次数
  • list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
  • list.reverse() 反转列表
  • list.sort([reverse=False]) 排序
  • list.extend(list) 在列表后面追加一个列表

4.6 列表相关函数

  • len(list) 求列表长度
  • max(list) 返回列表中最大值
  • min(list) 返回列表中最小值

4.7 列表练习题

1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量

2. 用列表模拟队列

3. 用列表模拟堆栈

4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]
答案:
l.sort(key=lambda item:item['age'])
print(l)

5 字典操作

5.1 删除字典成员

  • del dict[key] 删除指定
  • dict.clear() 删除所有
  • dict.pop(key) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值
  • dict.popitem() 随机删除字典中的一个(实际上删除最后一个)

5.2 字典key-value操作

  • dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值
  • dict.__contains__(key) 如果键在字典dict里返回true,否则返回false
  • dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default

5.3 字典其他操作方法

  • dict.items() 以列表返回可遍历的(键, 值) 元组数组
  • dict.values() 以列表返回字典中的所有值
  • dict.keys() 以列表返回一个字典所有的键
  • dict.copy() 返回一个字典的浅复制
  • dict.update(dict2) 把字典dict2的键/值对更新到dict里
  • dict.fromkeys(seq[, val])创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值

5.4 字典练习

#简单购物车,要求如下:
#实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
#购物列表中的每个元素都是 tuple 成员是 商品名 价格 购买个数

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods_l=[]
while True:
    for key,item in msg_dic.items():
        print('name:{name} price:{price}'.format(price=item,name=key))
    choice=input('商品>>: ').strip()
    if not choice or choice not in msg_dic:continue
    count=input('购买个数>>: ').strip()
    if not count.isdigit():continue
    goods_l.append((choice,msg_dic[choice],count))

    print(goods_l)
# 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

#即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
    if i>66:
        a['k1'].append(i)
    else:
        a['k2'].append(i)
print(a)
#2 统计s='hello alan alan say hello sb sb'中每个单词的个数

#第一种写法
l=s.split()
dic={}
for item in l:
    if item in dic:
        dic[item]+=1
    else:
        dic[item]=1
print(dic)

#第二种写法
s='hello alan alan say hello sb sb'
dic={}
words=s.split()
for word in words: 
    dic[word]=s.count(word)
print(dic)

#第三种写法
s='hello alan alan say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
    dic.setdefault(word,s.count(word))
print(dic)
#3: 三级菜单
#要求:
打印省、市、县三级菜单
可返回上一级
可随时退出程序

menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '黄浦':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闵行':{
            '七宝':{
                '交通大学':{},
                '七宝老街':{}
            },
            '虹桥':{
                '飞机场':{},
                '高铁站':{}
            }
        },
        '闸北':{
            '彭浦新村':{
                '彭浦公园':{}
            },
            '大宁':{
                '灵石公园':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



layers=[menu,]

while True:
    if len(layers) == 0: break
    current_layer=layers[-1]
    for key in current_layer:
        print(key)

    choice=input('>>: ').strip()

    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break

    if choice not in current_layer:continue

    layers.append(current_layer[choice])

results matching ""

    No results matching ""