Python基础_05

Python基础_05

一、元祖

  • 元祖(tuple):
    和列表类似
    元祖是不可变的有序序列
    数据元素确定且不会再发生变化就可以使用元祖
    元祖的数据标记是()
    注意:一元组定义时,元素后必须加逗号,否则会识别成提高表达式优先级
month = int(input('请输入月份:'))
year = int(input('请输入年份:'))
if month in (4, 6, 9, 11):
    print(month, '月有30天')
elif month in (1, 3, 5, 7, 8, 10, 12):
    print(month, '月有31天')
else:
    if (year % 4 == 0 and year % 400) or (year % 400 == 0):
        print(month, '月有29天')
    else:
        print(month, '月有28天')
# 当给一个变量赋值时使用逗号分隔开多个数据,这多个数据进行打包操作,打包成元组赋值给变量
values = 11, 23, 56, 66
print(type(values))  # <class 'tuple'>

二、字符串

  • 字符串是容器型数据,里面的元素都是字符【长度为1的字符】
    不可变的有序序列
  • 获取的操作:
    1.字符串数据.find(子串)
    查找子串第一次出现的位置
    2.字符串数据.rfind(子串)
    查找子串最后一次出现的位置
    3.字符串数据.count(子串)
    统计子串出现的次数
s = 'hello everyone'
pop = s.find('e')
print(pop)   # 1

pos = s.rfind('e')
print(pos)  # 13

count = s.count('e')
print(count)  # 4
  • 转换的操作:
    转换后产生的是一个新的数据
    字符串数据.upper() 将字母变大写
    字符串数据.lower() 将字母变小写
    字符串数据.swapcase() 将大写变小写,将小写变大写
    字符串数据.title() 将每个单词首字母大写【没连在一起视为一个新单词】
    字符串数据.capitalize() 首字母大写,其余小写
s = 'hello everyone'
new_s = s.upper()
print(s, new_s)

new_s1 = new_s.lower()
print(new_s1)

new_s2 = new_s.title()
print(new_s2)  # Hello Everyone

new_s3 = new_s2.swapcase()
print(new_s3)

new_s4 = new_s3.capitalize()
print(new_s4)
  • 判断的操作:
    1. 是否以指定内容开头
    字符串数据.startswith(指定内容)
    2. 是否以指定内容结尾
    字符串数据.endswith(指定内容)
    3. 判断是否是纯数字
    字符串数据.isdigit()
    4. 判断字符串的内容是否为纯字母
    字符串数据.isalpha()
    5. 判断字符串的内容是否为数字或字母
    字符串数据.isalnum()
    6. 判断字符串中的字母是否为大写
    字符串数据.isupper()
    7. 判断字符串中的字母是否为小写
    字符串数据.islower()
s = 'Hello Everyone'
print(s.startswith('H'))
print(s.endswith('one'))

print(s.isalnum())  # False
print(s.isalpha())  # False
print(s[0].isupper())  # True
print(s[-3:].islower())  # True

print('123'.isdigit())

print('abc12'.isdigit())
  • 字符串的切割和拼接
    切割:
    字符串数据.split(切割符)
    将指定切割符为切割点,把字符串分为N份,结果是一个列表,存储多个子串
    拼接:
    ‘拼接符’.join(容器型数据)
    使用拼接符将容器中的元素拼接在一起
    注意:拼接的元素必须是字符串类型
data = "hello my age is 18, my birthday is September 5th."
print(data)
print(data.split(' '))
# ['hello', 'my', 'age', 'is', '18,', 'my', 'birthday', 'is', 'September', '5th.']

print(data.split('e'))

nums = [18, 34, 56, 71, 29]
# 使用+号将其拼接在一起
# print('+'.join(nums))
# TypeError: sequence item 0: expected str instance, int found
# 人家期待的是字符串 但是获取的却是整型

# 拼接之前转化成字符串
# str(nums)  # 将传进的数据转化为字符串 ====> '[18, 34, 56, 71, 29]'
str_nums = [str(ele) for ele in nums]  # ['18', '34', '56', '71', '29']
print('+'.join(str_nums))  # 18+34+56+71+29
  • 字符串格式化
    在指定宽度中居中显示 字符串.center(宽度, 占位符)
    在指定宽度中居左显示 字符串.ljust(宽度, 占位符)
    在指定宽度中居右显示 字符串.rjust(宽度, 占位符)
s = 'hello'
print(s.center(10, '*'))  # **hello***
print(s.ljust(10, '*'))  # hello*****
print(s.rjust(10, '*'))  # *****hello
  • 将未知的数据格式化拼接在字符串文本中
    目的:将非字符串类型的数据与字符串类型的数据进行拼接
# 方式1:将数据转换为字符串类型
print('年龄' + str(17))

# 方式2:使用字符串中%运算符
"""
先生成文本 在未知的位置使用占位进行占位,再对字符串进行%, 给占位的符号赋值
    占位符:
        %s --- 可以填充任意类型的数据
        %d --- 填充的是整型数据
            可以单独再进行格式化操作
                %0nd  === n代表的是数字显式的宽度 不足n位 左边补充0
                    %05d ====> 10 ====> 显式的时候 为 00010
        %f --- 填充的浮点型数据
            可以再单独格式化 
                %.nf === n代表的是保留小数的位数
                    %.3f ====> 3.1415926 ===>显式为 3.142
"""
year = 2020
month = 4
if month in (4, 6, 9, 11):
    day = 30
elif month in (1, 3, 5, 7, 8, 10, 12):
    day = 31
else:
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        day = 29
    else:
        day = 28
# 有几个占位符 就赋予几个值  值和占位符之间是一一对应的
content = '%s年%s月有%s天' % (year, month, day)
print(content)


# 学号  显式的时候按照6位来显式
sid = 1
# 姓名
name = '张三'
# 年龄
age = 17
# 成绩  显式的时候保留一位小数
score = 89.65
info = '学号为%06d的%s,年龄是%s, 考试成绩为%.1f' % (sid, name, age, score)
print(info)

# 方式3: 字符串数据.format()
"""
先生成字符串文本数据,未知数据的地方使用 {}进行占位 调用字符串的format操作 给占位符进行赋值
有几个占位符 传递就有几个值
    如果对数据有特殊的格式 在{}操作
        {:0nd}  按照n位填充
        {:.nf}  保留n位小数
"""
info1 = '学号为{:06d}的{}, 年龄是{}, 考试成绩为{:.1f}'.format(sid, name, age, score)
print(info1)


# 方式4: 是方式3的简化  使用f修饰字符串
# f修饰完字符串  可以直接在{}的位置填充对应的数据值
# 要修饰数据 {数据:0nd}   {数据:.nf}
info2 = f'学号为{sid:06d}{name}, 年龄是{age}, 考试成绩是{score:.1f}'
print(info2)

三、字典

  • 为了更方便表达数据的含义,可以使用字典来进行存储
    {key:value, key:value}
    会给每一个数据设置标记,通过标记名获取对应的数据值
    字典是使用键值对进行数据的存储,通过键定位值,要求键不允许重复,键的内容一旦确定不允许变

    字典是无序的可变序列
    无序:元素没有位置编号
    可变:数据值可以修改 可以增加新的键值对 删除键值对

air_temp = {'7点': 17, '9点': 20, '11点': 26, '14点': 30, '16点': 25, '18点': 22}
print(air_temp)

# 获取数据通过标记名取值
print(air_temp['11点'])
# 如果键不存在就报错
# print(air_temp['10点'])
# KeyError: '10点'

# 获取数据值推荐方式
print(air_temp.get('11点'), air_temp.get('10点'))   # 26 None

# 获取键值对的个数
print(len(air_temp))  # 6

# 添加新的键值对
air_temp.setdefault('19点', 20)  # 影响的是原数据
print(air_temp)

# 移除键值对
air_temp.pop('11点')
print(air_temp)

# 修改
air_temp['19点'] = 18
print(air_temp)

# air_temp.clear() 清空

# 遍历
# 直接遍历字典 遍历的是字典中的键  [直接对字典进行成员操作 获取的是键]
for ele in air_temp:
    print(ele, air_temp.get(ele))

# 等价于
print(air_temp.keys())  # 字典中所有的键  dict_keys(['7点', '9点', '14点', '16点', '18点', '19点'])
for k in air_temp.keys():
    print(k)

print('============')
# 单独拿值
print(air_temp.values())  # dict_values([17, 20, 30, 25, 22, 20])
for v in air_temp.values():
    print(v)

print('============')
# 获取字典中键值组合
print(air_temp.items())  # dict_items([('7点', 17), ('9点', 20), ('14点', 30), ('16点', 25), ('18点', 22), ('19点', 20)])
for item in air_temp.items():
    print(item)
print('============')
for k, v in air_temp.items():
    print(k, v)

三、字典的案例

  • 词频统计
    词/字符/数字 出现的个数 或者对数据进行归类
s = 'good good study day day up'
print(s)
"""
思路:
    1.遍历字符串  获取每个字符
    2.把字符出现的个数存储字典中 【字符为键 个数为值】
    
"""
count_dict = {}
for ch in s:
    if ch not in count_dict:
        count_dict.setdefault(ch, 1)
    else:
        count_dict[ch] = count_dict.get(ch) + 1
print(count_dict)

# 归类
nums = [19, 27, 38, 41, 25, 66, 24, 32, 51]
# 偶数为一类  奇数为一类
classify_dict = {'even': [], 'odd': []}
for ele in nums:
    if ele % 2 == 0:
        classify_dict['even'].append(ele)
    else:
        classify_dict['odd'].append(ele)
print(classify_dict)

# 奇数的个数和偶数的个数
classify_dict1 = {'even': 0, 'odd': 0}
for ele1 in nums:
    if ele1 % 2 == 0:
        classify_dict1['even'] += 1
    else:
        classify_dict1['odd'] += 1
print(classify_dict1)
# 字典数据的过滤
dict0 = {'hello': 1, 'nice': 3, 'to': 2, 'meet': 2, 'you': 2, 'too': 1, 'good': 1, 'fine': 1}
print(dict0)
new_dict = {}
for k, v in dict0.items():
    if v == 1:
        new_dict.setdefault(k, v)
print(new_dict)

# 字典推导式
# 字典中存放的是键值对  key:value
print({k: v for k, v in dict0.items() if v == 1})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值