1 Star 1 Fork 0

方泽斌/Python学习笔记

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

Python

一、字典、集合方法总结

字典

字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值 key=>value 对用冒号 : 分割,每个对之间用逗号 , 分割,整个字典包括在花括号 {} 中。

d = {key1 : value1, key2 : value2 }

值可以取任何数据类型,但键必须是不可变的,如:str、number、tuple。

1.字典三种创建方式

info = {
    "stu1": "AAA",
    "stu2": "BBB",
    "stu3": "CCC"
}
# 先建个空字典,然后加值进去
info_2021 = {}
info_2021["stu21_1"] = "DDD"
info_03 = dict(stu1="AAA", stu2="BBB", stu3="CCC")

2.访问字典里的值
把相应的键放入到方括号中。

dict = {'name': 'Dillon', 'age': 19}
 
print ("dict['name']: ", dict['name'])
print ("dict['age']: ", dict['age'])
dict['name']:  Dillon
dict['age']:  19

3.修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对。

dict = {'name': 'Dillon', 'age': 18}
 
dict['age'] = 19           # 更新 Age
dict['school'] = "中大南方"  # 添加信息
print ("dict['age']: ", dict['age'])
print ("dict['school']: ", dict['school'])
dict['age']:  19
dict['school']:  中大南方

4.删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。 显示删除一个字典用del命令。

dict = {'name': 'Dillon', 'age': 19}
 
del dict['name'] # 删除键 'name'
dict.clear()     # 清空字典
del dict         # 删除字典

5.字典键的特性
字典值可以是任何的 python 对象,既可以是标准的对象,也可以是用户定义的,但键不行。

  • 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住。
dict = {'name': 'Dillon', 'age': 19, 'name': 'D'}
 
print ("dict['name']: ", dict['name'])
dict['name']:  D
  • 键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行。
dict = {['name']: 'Dillon', 'age': 19}
 
print ("dict['name']: ", dict['name'])
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['name']: 'Dillon', 'age': 19}
TypeError: unhashable type: 'list'

字典内置函数&方法

Python字典包含了以下内置函数:

函数 描述
len(dict) 计算字典元素个数,即键的总数。
str(dict) 输出字典,以可打印的字符串表示
type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:

函数 描述
radiansdict.clear() 删除字典内所有元素
radiansdict.copy() 返回一个字典的浅复制
radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None) 返回指定键的值,如果键不在字典中返回 default 设置的默认值
key in dict 如果键在字典dict里返回true,否则返回false
radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() 返回一个迭代器,可以使用 list() 来转换为列表
radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里
radiansdict.values() 返回一个迭代器,可以使用 list() 来转换为列表
pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
popitem() 随机返回并删除字典中的最后一对键和值。

集合

集合(set)是一个无序不重复元素序列。 可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

创建格式:

parame = {value01, value02}
set(value)

集合的基本操作

1.添加元素

s.add( x )

将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}

还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等。

s.update(x)

x 可以有多个,用逗号分开。

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Runoob'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}

2.移除元素

s.remove( x )

将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Runoob'}
>>> thisset.remove("Facebook")   # 不存在会发生错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Facebook'

此外还有一个方法也是移除集合中的元素,且如果元素不存在,不会发生错误。

s.discard( x )
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.discard("Facebook")  # 不存在不会发生错误
>>> print(thisset)
{'Taobao', 'Google', 'Runoob'}

我们也可以设置随机删除集合中的一个元素。

s.pop() 

set 集合的 pop 方法会对集合进行无序的排列,然后将这个无序排列集合的左面第一个元素进行删除。

3、计算集合元素个数

len(s)
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> len(thisset)
3

4、清空集合

s.clear()
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()

5、判断元素是否在集合中存在 语法格式如下:

x in s

判断元素 x 是否在集合 s 中,存在返回 True,不存在返回 False。

>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> "Runoob" in thisset
True
>>> "Facebook" in thisset
False

6、集合间的运算

>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a 
{'a', 'r', 'b', 'c', 'd'}
>>> a - b   # 集合a中包含而集合b中不包含的元素
{'r', 'd', 'b'}
>>> a | b   # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b   # 集合a和b中都包含了的元素
{'a', 'c'}
>>> a ^ b   # 不同时包含于a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'}

集合内置方法完整列表

方法 描述
add() 为集合添加元素
clear() 移除集合中的所有元素
copy() 拷贝一个集合
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
discard() 删除集合中指定的元素
intersection() 返回集合的交集
intersection_update() 返回集合的交集。
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
issubset() 判断指定集合是否为该方法参数集合的子集。
issuperset() 判断该方法的参数集合是否为指定集合的子集
pop() 随机移除元素
remove() 移除指定元素
symmetric_difference() 返回两个集合中不重复的元素集合。
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。
union() 返回两个集合的并集
update() 给集合添加元素

二、猜数字练习

import getpass
card = int(getpass.getpass("请输入数字:"))
count = 0
while True:
    if count < 3:
        guess = int(input("请输入你猜测的数字:"))
        # 对比数字和猜测数字的大小
        if card == guess:
            print("Good job!")
            break
        elif card > guess:
            print("Bigger.")
        else:
            print("Smaller.")
    else:
        print("哈哈哈哈~猜了这么多次都猜不出来,你好笨啊~")
        break
    count = count + 1

# GetPassWarning: Can not control echo on the terminal.
#   passwd = fallback_getpass(prompt, stream)
# Warning: Password input may be echoed.
# 请输入数字:55
#
# 请输入你猜测的数字:12
# Bigger.
# 请输入你猜测的数字:56
# Smaller.
# 请输入你猜测的数字:57
# Smaller.
# 哈哈哈哈~猜了这么多次都猜不出来,你好笨啊~

三、课本代码练习

代码见:

vowels = ['a', 'e', 'i', 'o', 'u']
word = input("Provide a word to search for vowels: ")

found = {}

found['a'] = 0
found['e'] = 0
found['i'] = 0
found['o'] = 0
found['u'] = 0

for letter in word:
    if letter in vowels:
        found[letter] += 1

for k, v in sorted(found.items()):
    print(k, 'was found', v, 'time(s)')

# Provide a word to search for vowels: Password input may be echoed.
# a was found 2 time(s)
# e was found 3 time(s)
# i was found 1 time(s)
# o was found 2 time(s)
# u was found 1 time(s)
vowels = ['a', 'e', 'i', 'o', 'u']
word = input("Provide a word to search for vowels: ")

found = {}

for letter in word:
    if letter in vowels:
        found[letter] += 1

for k, v in sorted(found.items()):
    print(k, 'was found', v, 'time(s)')

# Provide a word to search for vowels: Password input may be echoed.
# Traceback (most recent call last):
#   File "/Users/apple/PycharmProjects/w6/vowels5.py", line 8, in <module>
#     found[letter] += 1
# KeyError: 'a'
vowels = ['a', 'e', 'i', 'o', 'u']
word = input("Provide a word to search for vowels: ")

found = {}

for letter in word:
    if letter in vowels:
        found.setdefault(letter, 0)
        # setdefault() 函数和 get()方法 类似, 如果键不存在于字典中,将会添加键并将值设为默认值。
        found[letter] += 1

for k, v in sorted(found.items()):
    print(k, 'was found', v, 'time(s)')

# Provide a word to search for vowels: Password input may be echoed.
# a was found 2 time(s)
# e was found 3 time(s)
# i was found 1 time(s)
# o was found 2 time(s)
# u was found 1 time(s)

vowels = set('aeiou')
word = input("Provide a word to search for vowels: ")
found = vowels.intersection(set(word))
for vowel in found:
    print(vowel)

# Provide a word to search for vowels: Password input may be echoed.
# e
# a
# o
# u
# i

四、字典查询练习

Azure API 提供一张含有>=3张脸(3个以上faceid)的图片,先用json()获取内容(results),在用数据结构查询的方式查找到:眼镜、肤色、微笑指数、头发颜色、年龄、性别这几项数据,并分别存进变量/自定义数据结构(如字典等)当中。

代码见:

r = [{'faceId': '1e4ab4e8-b146-4d1c-b199-0244808902c6',
  'faceRectangle': {'top': 118, 'left': 144, 'width': 88, 'height': 88},
  'faceAttributes': {'smile': 0.813,
   'gender': 'male',
   'age': 19.0,
   'glasses': 'NoGlasses',
   'hair': {'bald': 0.18,
    'invisible': False,
    'hairColor': [{'color': 'brown', 'confidence': 0.95},
     {'color': 'black', 'confidence': 0.93},
     {'color': 'other', 'confidence': 0.23},
     {'color': 'blond', 'confidence': 0.23},
     {'color': 'gray', 'confidence': 0.21},
     {'color': 'red', 'confidence': 0.15},
     {'color': 'white', 'confidence': 0.0}]}}},
 {'faceId': '3649cc3a-6fea-415c-96af-216985d159d0',
  'faceRectangle': {'top': 117, 'left': 376, 'width': 64, 'height': 64},
  'faceAttributes': {'smile': 0.456,
   'gender': 'female',
   'age': 22.0,
   'glasses': 'NoGlasses',
   'hair': {'bald': 0.08,
    'invisible': False,
    'hairColor': [{'color': 'black', 'confidence': 1.0},
     {'color': 'other', 'confidence': 0.63},
     {'color': 'brown', 'confidence': 0.46},
     {'color': 'gray', 'confidence': 0.39},
     {'color': 'blond', 'confidence': 0.03},
     {'color': 'red', 'confidence': 0.01},
     {'color': 'white', 'confidence': 0.0}]}}},
 {'faceId': 'cbb83b49-7744-4233-bf3d-3d650fe2522c',
  'faceRectangle': {'top': 41, 'left': 676, 'width': 52, 'height': 52},
  'faceAttributes': {'smile': 1.0,
   'gender': 'male',
   'age': 25.0,
   'glasses': 'ReadingGlasses',
   'hair': {'bald': 0.06,
    'invisible': False,
    'hairColor': [{'color': 'black', 'confidence': 0.98},
     {'color': 'brown', 'confidence': 0.96},
     {'color': 'other', 'confidence': 0.22},
     {'color': 'gray', 'confidence': 0.21},
     {'color': 'red', 'confidence': 0.09},
     {'color': 'blond', 'confidence': 0.08},
     {'color': 'white', 'confidence': 0.0}]}}},
 {'faceId': 'a53220d9-d1ad-49c4-aff2-60b29d7b5395',
  'faceRectangle': {'top': 69, 'left': 445, 'width': 52, 'height': 52},
  'faceAttributes': {'smile': 1.0,
   'gender': 'female',
   'age': 23.0,
   'glasses': 'NoGlasses',
   'hair': {'bald': 0.11,
    'invisible': False,
    'hairColor': [{'color': 'black', 'confidence': 1.0},
     {'color': 'brown', 'confidence': 0.81},
     {'color': 'other', 'confidence': 0.41},
     {'color': 'gray', 'confidence': 0.37},
     {'color': 'blond', 'confidence': 0.03},
     {'color': 'red', 'confidence': 0.02},
     {'color': 'white', 'confidence': 0.0}]}}},
 {'faceId': 'c9dab554-30b5-46ab-985a-51312dfbd1b9',
  'faceRectangle': {'top': 95, 'left': 238, 'width': 51, 'height': 51},
  'faceAttributes': {'smile': 0.981,
   'gender': 'female',
   'age': 18.0,
   'glasses': 'ReadingGlasses',
   'hair': {'bald': 0.11,
    'invisible': False,
    'hairColor': [{'color': 'black', 'confidence': 0.98},
     {'color': 'brown', 'confidence': 0.86},
     {'color': 'other', 'confidence': 0.4},
     {'color': 'gray', 'confidence': 0.36},
     {'color': 'blond', 'confidence': 0.09},
     {'color': 'red', 'confidence': 0.08},
     {'color': 'white', 'confidence': 0.0}]}}},
 {'faceId': 'c2f4dfce-a532-47f6-b197-2aa794df5bc5',
  'faceRectangle': {'top': 94, 'left': 540, 'width': 48, 'height': 48},
  'faceAttributes': {'smile': 1.0,
   'gender': 'female',
   'age': 19.0,
   'glasses': 'NoGlasses',
   'hair': {'bald': 0.1,
    'invisible': False,
    'hairColor': [{'color': 'black', 'confidence': 1.0},
     {'color': 'brown', 'confidence': 0.88},
     {'color': 'other', 'confidence': 0.35},
     {'color': 'gray', 'confidence': 0.33},
     {'color': 'blond', 'confidence': 0.05},
     {'color': 'red', 'confidence': 0.04},
     {'color': 'white', 'confidence': 0.0}]}}}]

# 创建字典
glasses = {}
smile = {}
hairColor = {}
age = {}
gender = {}

# 把所有人脸的值添加进字典
count = 0
while count < len(r):
    glasses["Person{}".format(count + 1)] = r[count]['faceAttributes']['glasses']
    smile["Person{}".format(count + 1)] = r[count]['faceAttributes']['smile']
    hairColor["Person{}".format(count + 1)] = r[count]['faceAttributes']['hair']['hairColor'][0]['color']
    age["Person{}".format(count + 1)] = r[count]['faceAttributes']['age']
    gender["Person{}".format(count + 1)] = r[count]['faceAttributes']['gender']
    count += 1

# 打印字典
print("眼镜:", glasses)
print("微笑指数:", smile)
print("头发颜色:", hairColor)
print("年龄:", age)
print("性别:", gender)

# 眼镜: {'Person1': 'NoGlasses', 'Person2': 'NoGlasses', 'Person3': 'ReadingGlasses', 'Person4': 'NoGlasses', 'Person5': 'ReadingGlasses', 'Person6': 'NoGlasses'}
# 微笑指数: {'Person1': 0.813, 'Person2': 0.456, 'Person3': 1.0, 'Person4': 1.0, 'Person5': 0.981, 'Person6': 1.0}
# 头发颜色: {'Person1': 'brown', 'Person2': 'black', 'Person3': 'black', 'Person4': 'black', 'Person5': 'black', 'Person6': 'black'}
# 年龄: {'Person1': 19.0, 'Person2': 22.0, 'Person3': 25.0, 'Person4': 23.0, 'Person5': 18.0, 'Person6': 19.0}
# 性别: {'Person1': 'male', 'Person2': 'female', 'Person3': 'male', 'Person4': 'female', 'Person5': 'female', 'Person6': 'female'}


笔记

列表list/元组tuple

  • 代码从左往右运行 先运行括号内的_
  • 列表中的每个值都有对应的位置值,称之为索引,第一个索引是 0,第二个索引是 1,依此类推。
  • 列表的数据项不需要具有相同的类型。
  • Python 有 6 个序列的内置类型,但最常见的是列表和元组。
  • 列表的复制与变量的复制不一样(.copy 浅复制,不能完全复制) (first[5].append(4))
  • 列表的切片,不会改变源列表
  • plist 变成列表(!空格也算一个字符)
  • extend 只能扩展列表(如将plist进行extend)
  • 拼接 ().join (可拼接列表里两个内容)
  • index 索引元素第一次出现的位置
  • tuple元组不可变 a = (1,2,3,[])元组里列表可变
  • .popleft()
list.append(obj) 在列表末尾添加新的对象 list.count(obj) 统计某个元素在列表中出现的次数
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj) 将对象插入列表 list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项 list.reverse() 反向列表中元素
list.sort( key=None, reverse=False) 对原列表进行排序 list.clear() 清空列表
list.copy() 复制列表
Python 表达式 结果 描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复
3 in [1, 2, 3] True 元素是否存在于列表中
for x in [1, 2, 3]: print(x, end=" ") 1 2 3 迭代

字典dict

四种创建方式:

  1. dict = {"key" = "value"}直接建key:value
  2. dict = {} dict["key"] = "value"空字典加值(有未知的数值可以这样建)
  3. dict(key01=value01,...)
  4. dict.fromkeys(seq,value)
  • key唯一,key不可更改(str,num,tuple不可变可作为key),value可以.value可以是仍以对象的数据
  • 字典的查询:print(“key” in dict),print(dict["key"])注意层级关系!!!/get
  • dict查询比list快
  • dict.keys()查看标签判断内容/dict.values()判断数据格式
  • dict.setdefault(key,0) dict[key] +=1 ————示例:购物车如果已经加入一件可以增加
函数 描述
dict.keys() 以列表返回一个字典所有的键
dict.setdefault(key, default=None) 如果键不存在于字典中,将会添加键并将值设为default
dict.fromkeys(seq[, val]) 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
dict.items() 以列表返回可遍历的(键, 值) 元组数组
dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值
dict.update(dict2) 把字典dict2的键/值对更新到dict里
dict.pop("key") 指定删除
dict.popitem() 随机删除
dict.clear() 删除字典内所有元素

集合set

  • 可以用运算符直接操作,也可以用方法
  • 应用场景:统计成绩/去重
方法 描述
add() 添加元素
clear() 移除所有元素
difference() 返回集合的差集
discard() 删除集合中指定的元素
intersection() 返回集合的交集
union() 返回两个集合的并集
update() 给集合添加元素

函数

  • 位置参数
  • 都是关键字参数(无序)(默认关键字参数,调用函数时可以不赋值)
  • 关键字参数和位置参数可以混合使用(关键字参数作为默认参数要放在位置参数后)
  • 有默认值避免bug
  • 数据的输入输出
  • 应用:节省代码,重复利用已有的相同功能

Python学习笔记

介绍

本仓库用于存放学习Python语言的学习笔记

一、获取当前日期

1、>>>import datetime
>>>datetime date.today()
datetime.date(2020, 11, 1)
>>> datetime.date.today().day
1
>>> datetime.date.today().month
11
>>> datetime.date.today().year
2020

1.1、>>> datetime.date.now()
Traceback (most recent call last):
  File "<pyshell#83>", line 1, in <module>
    datetime.date.now()
AttributeError: type object 'datetime.date' has no attribute 'now'

>>> datetime.date.now().year
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    datetime.date.now().year
AttributeError: type object 'datetime.date' has no attribute 'now'

>>> datetime.date.now().month
Traceback (most recent call last):
  File "<pyshell#85>", line 1, in <module>
    datetime.date.now().month
AttributeError: type object 'datetime.date' has no attribute 'now'

>>> datetime.date.now().day
Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    datetime.date.now().day
AttributeError: type object 'datetime.date' has no attribute 'now'
2、>> datetime.datetime.today()
datetime.datetime(2020, 11, 1, 11, 8, 20, 567838)
>>> datetime.datetime.today().year
2020
>>> datetime.datetime.today().month
11
>>> datetime.datetime.today().day
1
2.1、>>> datetime.datetime.now()
datetime.datetime(2020, 11, 1, 10, 49, 15, 333100)
>>> datetime.datetime.now().year
2020
>>> datetime.datetime.now().month
11
>>> datetime.datetime.now().day
1

二、if条件语句:

1.猜猜游戏

print("猜猜游戏")
shuru=input("请输入一个数字")
shuru=int(shuru)
if shuru==8:
    print("我是帅哥")
elif shuru==10:
    print("我是美女")
else:
    print("我是码农")
    print("游戏结束")
>>>猜猜游戏
   请输入一个数字8
   我是帅哥

备注: 语句中的shuru=int(shuru)至关重要, 没有shuru=int(shuru), 运行结果是以下这样的 解释器没有执行if和elif的代码

猜猜游戏
请输入一个数字8
我是码农
游戏结束
>>> 
==================== RESTART: C:/Users/方泽斌/Desktop/11.1.1.py ===================
>>> 
猜猜游戏
请输入一个数字10
我是码农
游戏结束
>>> 
==================== RESTART: C:/Users/方泽斌/Desktop/11.1.1.py ===================
>>> 
猜猜游戏
请输入一个数字2
我是码农
游戏结束
>>> 

三、for循环

1.循环迭代数字变量

>>> for i in [1,2,3]:
	print(i)
1
2
3

2.循环迭代字符串

>>> for i in "fangzebin":
	print(i)	
f
a
n
g
z
e
b
i
n

3.迭代指定的次数

>>> for i in range(10):
	print("fangzebin")
fangzebin
fangzebin
fangzebin
fangzebin
fangzebin
fangzebin
fangzebin
fangzebin
fangzebin
fangzebin
>>> for i in range(10):
	print(i)
0
1
2
3
4
5
6
7
8
9
>>> for i in range(10):
	print(10)
10
10
10
10
10
10
10
10
10
10

4.用for循环求解1+2+3+...+1000的值

>>> begin=0
>>> for i in range(1001):
	begin=begin+i
	print(begin)

0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 325 351 378 406 435 465 496 528 561 595 630 666 703 741 780 820 861 903 946 990 1035 1081 1128 1176 1225 1275 1326 1378 1431 1485 1540 1596 1653 1711 1770 1830 1891 1953 2016 2080 2145 2211 2278 2346 2415 2485 2556 2628 2701 2775 2850 2926 3003 3081 3160 3240 3321 3403 3486 3570 3655 3741 3828 3916 4005 4095 4186 4278 4371 4465 4560 4656 4753 4851 4950 5050 5151 5253 5356 5460 5565 5671 5778 5886 5995 6105 6216 6328 6441 6555 6670 6786 6903 7021 7140 7260 7381 7503 7626 7750 7875 8001 8128 8256 8385 8515 8646 8778 8911 9045 9180 9316 9453 9591 9730 9870 10011 10153 10296 10440 10585 10731 10878 11026 11175 11325 11476 11628 11781 11935 12090 12246 12403 12561 12720 12880 13041 13203 13366 13530 13695 13861 14028 14196 14365 14535 14706 14878 15051 15225 15400 15576 15753 15931 16110 16290 16471 16653 16836 17020 17205 17391 17578 17766 17955 18145 18336 18528 18721 18915 19110 19306 19503 19701 19900 20100 20301 20503 20706 20910 21115 21321 21528 21736 21945 22155 22366 22578 22791 23005 23220 23436 23653 23871 24090 24310 24531 24753 24976 25200 25425 25651 25878 26106 26335 26565 26796 27028 27261 27495 27730 27966 28203 28441 28680 28920 29161 29403 29646 29890 30135 30381 30628 30876 31125 31375 31626 31878 32131 32385 32640 32896 33153 33411 33670 33930 34191 34453 34716 34980 35245 35511 35778 36046 36315 36585 36856 37128 37401 37675 37950 38226 38503 38781 39060 39340 39621 39903 40186 40470 40755 41041 41328 41616 41905 42195 42486 42778 43071 43365 43660 43956 44253 44551 44850 45150 45451 45753 46056 46360 46665 46971 47278 47586 47895 48205 48516 48828 49141 49455 49770 50086 50403 50721 51040 51360 51681 52003 52326 52650 52975 53301 53628 53956 54285 54615 54946 55278 55611 55945 56280 56616 56953 57291 57630 57970 58311 58653 58996 59340 59685 60031 60378 60726 61075 61425 61776 62128 62481 62835 63190 63546 63903 64261 64620 64980 65341 65703 66066 66430 66795 67161 67528 67896 68265 68635 69006 69378 69751 70125 70500 70876 71253 71631 72010 72390 72771 73153 73536 73920 74305 74691 75078 75466 75855 76245 76636 77028 77421 77815 78210 78606 79003 79401 79800 80200 80601 81003 81406 81810 82215 82621 83028 83436 83845 84255 84666 85078 85491 85905 86320 86736 87153 87571 87990 88410 88831 89253 89676 90100 90525 90951 91378 91806 92235 92665 93096 93528 93961 94395 94830 95266 95703 96141 96580 97020 97461 97903 98346 98790 99235 99681 100128 100576 101025 101475 101926 102378 102831 103285 103740 104196 104653 105111 105570 106030 106491 106953 107416 107880 108345 108811 109278 109746 110215 110685 111156 111628 112101 112575 113050 113526 114003 114481 114960 115440 115921 116403 116886 117370 117855 118341 118828 119316 119805 120295 120786 121278 121771 122265 122760 123256 123753 124251 124750 125250 125751 126253 126756 127260 127765 128271 128778 129286 129795 130305 130816 131328 131841 132355 132870 133386 133903 134421 134940 135460 135981 136503 137026 137550 138075 138601 139128 139656 140185 140715 141246 141778 142311 142845 143380 143916 144453 144991 145530 146070 146611 147153 147696 148240 148785 149331 149878 150426 150975 151525 152076 152628 153181 153735 154290 154846 155403 155961 156520 157080 157641 158203 158766 159330 159895 160461 161028 161596 162165 162735 163306 163878 164451 165025 165600 166176 166753 167331 167910 168490 169071 169653 170236 170820 171405 171991 172578 173166 173755 174345 174936 175528 176121 176715 177310 177906 178503 179101 179700 180300 180901 181503 182106 182710 183315 183921 184528 185136 185745 186355 186966 187578 188191 188805 189420 190036 190653 191271 191890 192510 193131 193753 194376 195000 195625 196251 196878 197506 198135 198765 199396 200028 200661 201295 201930 202566 203203 203841 204480 205120 205761 206403 207046 207690 208335 208981 209628 210276 210925 211575 212226 212878 213531 214185 214840 215496 216153 216811 217470 218130 218791 219453 220116 220780 221445 222111 222778 223446 224115 224785 225456 226128 226801 227475 228150 228826 229503 230181 230860 231540 232221 232903 233586 234270 234955 235641 236328 237016 237705 238395 239086 239778 240471 241165 241860 242556 243253 243951 244650 245350 246051 246753 247456 248160 248865 249571 250278 250986 251695 252405 253116 253828 254541 255255 255970 256686 257403 258121 258840 259560 260281 261003 261726 262450 263175 263901 264628 265356 266085 266815 267546 268278 269011 269745 270480 271216 271953 272691 273430 274170 274911 275653 276396 277140 277885 278631 279378 280126 280875 281625 282376 283128 283881 284635 285390 286146 286903 287661 288420 289180 289941 290703 291466 292230 292995 293761 294528 295296 296065 296835 297606 298378 299151 299925 300700 301476 302253 303031 303810 304590 305371 306153 306936 307720 308505 309291 310078 310866 311655 312445 313236 314028 314821 315615 316410 317206 318003 318801 319600 320400 321201 322003 322806 323610 324415 325221 326028 326836 327645 328455 329266 330078 330891 331705 332520 333336 334153 334971 335790 336610 337431 338253 339076 339900 340725 341551 342378 343206 344035 344865 345696 346528 347361 348195 349030 349866 350703 351541 352380 353220 354061 354903 355746 356590 357435 358281 359128 359976 360825 361675 362526 363378 364231 365085 365940 366796 367653 368511 369370 370230 371091 371953 372816 373680 374545 375411 376278 377146 378015 378885 379756 380628 381501 382375 383250 384126 385003 385881 386760 387640 388521 389403 390286 391170 392055 392941 393828 394716 395605 396495 397386 398278 399171 400065 400960 401856 402753 403651 404550 405450 406351 407253 408156 409060 409965 410871 411778 412686 413595 414505 415416 416328 417241 418155 419070 419986 420903 421821 422740 423660 424581 425503 426426 427350 428275 429201 430128 431056 431985 432915 433846 434778 435711 436645 437580 438516 439453 440391 441330 442270 443211 444153 445096 446040 446985 447931 448878 449826 450775 451725 452676 453628 454581 455535 456490 457446 458403 459361 460320 461280 462241 463203 464166 465130 466095 467061 468028 468996 469965 470935 471906 472878 473851 474825 475800 476776 477753 478731 479710 480690 481671 482653 483636 484620 485605 486591 487578 488566 489555 490545 491536 492528 493521 494515 495510 496506 497503 498501 499500 500500

四、处理结构化数据

1.随机取数

>>> import random
>>> random.randint(1,60)
1

2.字母变大小写

2.1字母变大写:

>>> "fangzebin".upper()
'FANGZEBIN'

2.2字母变小写

>>> "FANGZEBIN".lower()
'fangzebin'

3.列表

3.1创建列表

>>> a=[1,2,3,4,5,6,7,8,9]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b=[1,2,3,4,5,'fang','ze','bin']
>>> b
[1, 2, 3, 4, 5, 'fang', 'ze', 'bin']

3.2 append()方法,在列表的末尾添加一个对象

>>> a.append(10)
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> b.append("fangzebin")
>>> b
[1, 2, 3, 4, 5, 'fang', 'ze', 'bin', 'fangzebin']

3.3 extend()方法,在列表添加一个可以迭代的对象

>>> a.extend("fangzebin")
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n']
>>> b.extend("fangzebin")
>>> b
[1, 2, 3, 4, 5, 'fang', 'ze', 'bin', 'fangzebin', 'f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n']
>>> a.extend([10])
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n', 10]
>>> b.extend([10])
>>> b
[1, 2, 3, 4, 5, 'fang', 'ze', 'bin', 'fangzebin', 'f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n', 'f', 10]

3.4 insert()函数

a.insert(0,1)
>>> a
[1, 'fangzebin', 111, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n', 10]
>>> a.insert(0,"fangzebin")
>>> a
['fangzebin', 1, 'fangzebin', 111, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n', 10]

3.5 pop()函数 3.5.1 pop函数默认移除列表中最后一个元素

>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.pop()
5
>>> a
[1, 2, 3, 4]

3.5.2 pop元素可以移除列表上的任意元素

>>> a
[1, 2, 3, 4]
>>> a.pop(3)
4
>>> a
[1, 2, 3]

3.6列表的合并 3.6.1用+来合并列表

>>> a=[1,2,3,4]
>>> b=[5,6,7,8]
>>> c=a+b
>>> c
[1, 2, 3, 4, 5, 6, 7, 8]

3.6.2用+=来合并列表

>>> a+=b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]

备注:a+=b等同于a=a+b

3.7使用list()创建列表:使用list()可以将任何可迭代的数据转化成列表

>>> a=list()
>>> a
[]
>>> a=list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a=list("fangzebin")
>>> a
['f', 'a', 'n', 'g', 'z', 'e', 'b', 'i', 'n']
>>> b=list([10])
>>> b
[10]
>>> b=list([1,2,3,4,5,6])
>>> b
[1, 2, 3, 4, 5, 6]

3.8 range()创建整数列表,语法格式为range(|start|end|step|)

start参数:起始数字,默认是0 end参数:结尾数字 step参数:步长,默认为1

>>> list(range(2,15,2))
[2, 4, 6, 8, 10, 12, 14]
>>> list(range(15,3,-1))
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4]
>>> list(range(-3,-10,-3))
[-3, -6, -9]

3.9列表元素取值:

>>> list(range(2,15,2))
[2, 4, 6, 8, 10, 12, 14]
>>> list(range(15,3,-1))
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4]
>>> list(range(-3,-10,-3))
[-3, -6, -9]
>>> a=range(0,10)
>>> b=list(a)
>>> a
range(0, 10)
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> c=b[0]
>>> c
0
>>> d=b[9]
>>> d
9

3.9.1用random模块中的sample随机创建在区间1到10中包括5个元素的数组a

import random a=random.sample(range(1,10),5) a [4, 1, 6, 3, 7]

4、元组

4.1创建元组:

a=[1,2,3,4,5,6,7,8,9] a [1, 2, 3, 4, 5, 6, 7, 8, 9] a=1,2,3,4,5,6,7,8,9 a (1, 2, 3, 4, 5, 6, 7, 8, 9) 4.2元组中的方法:count和index 4.2.1 index()方法用于从元组找出对象第一个匹配项的索引位置,如果对象不在元组中会报一个异常

>>> a
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> a.index(2)
1
>>> a.index(5)
4
>>> a.index(10)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    a.index(10)
ValueError: tuple.index(x): x not in tuple

4.2.2 Python的count()方法用于统计元素中出现的次数

>>> a
(1, 2, 1, 2, 3, 4, 1, 2, 3, 1)
>>> a.count(2)
3
>>> a.count(1)
4

5.While循环:

5.1用While与列表写一个猜字的游戏:

import random
a=random.randint(1,100)
count=0
if a<100 and a>0:
    while True:
        if count<5:
            shuru=input("请输入你猜想的数字")
            shuru=int(shuru)
            if shuru==a:
                print("恭喜你,猜中了")
                break
            elif shuru>a:
                print("你猜的数字太大了")
            else:
                print("你猜的数字太小了")
            count+=1
        else:
                print("不对")
                print("正确答案:%s"%(hide_card))
                break
    else:
                print("请输入数字在0-99的数字")

请输入你猜想的数字25
你猜的数字太小了
请输入你猜想的数字25
你猜的数字太小了
请输入你猜想的数字99
你猜的数字太大了
请输入你猜想的数字52
你猜的数字太小了
请输入你猜想的数字2
你猜的数字太小了
不对

6、字典={字段名1:字段值,字段名2:字段值,字段名3:字段值} 6.1、创建字典

>>> info={
	"name":"fangzebin",
	"nianji":19,
	"zhuanye":"wangxin"
	}
>>> print(info)
{'name': 'fangzebin', 'nianji': 19, 'zhuanye': 'wangxin'}

6.2、访问字典里的值

>>> print("dict['Name']:",dict['Name'])
dict['Name']: Fangzebin
>>> print(dict['Name'])
Fangzebin
>>> print("dict['Age']:",dict['Age'])
dict['Age']: 7

6.3、替换、增加字典的新内容:

>>> dict={'Name':'Fangzebin','Age':7,'class':'wangxin'}
>>> dict['Age']=8
>>> dict['school']="zhongda"
>>> print("dict['Age']:",dict['Age'])
dict['Age']: 8
>>> print("dict['school']:",dict['school'])
dict['school']: zhongda
>>> print(dict)
{'Name': 'Fangzebin', 'Age': 8, 'class': 'wangxin', 'school': 'zhongda'}

6.4、删除字典

>>> del dict['Name']
>>> dict
{'Age': 8, 'class': 'wangxin', 'school': 'zhongda'}
>>> dict.clear()
>>> dict
{}
>>> dict
{}
>>> del dict
>>> dict
<class 'dict'>
>>> print(dict)
<class 'dict'>
>>> print(dict['Age'])
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    print(dict['Age'])
TypeError: 'type' object is not subscriptable

6.5字典的len()函数:计算字典元素的个数,即键的总数

>>> dict={'Name':'Fangzebin','Age':7}
>>> len(dict)
2
>>> dict={'Name':'Fangzebin','Age':7,'zhuanye':'wangxin'}
>>> len(dict)
3

5.4字典的str函数:输出字典可打印的字符串表示:

>>> dict={'Name':'Fangzebin','Age':7}
>>> str(dict)[0]
'{'

6.6频度计数器引用: 两种方式递增e的频度计数:

1、
>>> found={}
>>> found["a"]=0
>>> found["e"]=0
>>> found["i"]=0
>>> found["o"]=0
>>> found["u"]=0
>>> print(found)
{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
>>> found["e"]=found["e"]+1
>>> print(found)
{'a': 0, 'e': 1, 'i': 0, 'o': 0, 'u': 0}
2、
>>> found["e"]+=1
>>> print(found)
{'a': 0, 'e': 2, 'i': 0, 'o': 0, 'u': 0}
>>> for a in found:
	print(a,"is found",found[a],"times")
a is found 0 times
e is found 2 times
i is found 0 times
o is found 0 times
u is found 0 times

6.7、 sorted()内置方法 sorted内置方法不会改变你提供的数据的顺序,它只是返回这个数据的一个有序的副本

>>> print(found)
{'a': 0, 'e': 2, 'i': 0, 'o': 0, 'u': 0}
>>> for a in sorted(found):
	print(a,"is found",found[a],"time(s).")
a is found 0 time(s).
e is found 2 time(s).
i is found 0 time(s).
o is found 0 time(s).
u is found 0 time(s).
>>> print(found)
{'a': 0, 'e': 2, 'i': 0, 'o': 0, 'u': 0}
>>> print(found.items())
dict_items([('a', 0), ('e', 2), ('i', 0), ('o', 0), ('u', 0)])
>>> for a,b in sorted(found.items()):
	print(a,"is found",b,"time(s).")
a is found 0 time(s).
e is found 2 time(s).
i is found 0 time(s).
o is found 0 time(s).
u is found 0 time(s).

6.8、频度计数来统计字母数量案例:

words=["a","e","i","o","u"]
shuru=input("请输入一个字符串")
found={}
found["a"]=0
found["e"]=0
found["i"]=0
found["o"]=0
found["u"]=0
for i in words:
    if i in words:
        found[i]+=1
        for k,v in sorted(found.items()):
            print(k,"is found",v,"time(s).")
请输入一个字符串aa
a is found 1 time(s).
e is found 0 time(s).
i is found 0 time(s).
o is found 0 time(s).
u is found 0 time(s).
a is found 1 time(s).
e is found 1 time(s).
i is found 0 time(s).
o is found 0 time(s).
u is found 0 time(s).
a is found 1 time(s).
e is found 1 time(s).
i is found 1 time(s).
o is found 0 time(s).
u is found 0 time(s).
a is found 1 time(s).
e is found 1 time(s).
i is found 1 time(s).
o is found 1 time(s).
u is found 0 time(s).
a is found 1 time(s).
e is found 1 time(s).
i is found 1 time(s).
o is found 1 time(s).
u is found 1 time(s).

7.集合

7.1集合不允许有重复,集合是用大括号包围,集合中只有逗号,绝对没有冒号

>>> a={"a","e","i","o","u","a","u"}
>>> a
{'o', 'u', 'a', 'e', 'i'}

7.2集合中用set()函数可以快速创建一个集合(无序)

>>> a=set("fangzebin")
>>> a
{'g', 'n', 'f', 'a', 'z', 'b', 'e', 'i'}

7.3利用sorted()与list()函数将一个集合转化为一个有序的列表

>>> b=sorted(a)
>>> b
['a', 'b', 'e', 'f', 'g', 'i', 'n', 'z']
>>> c=list(b)
>>> c
['a', 'b', 'e', 'f', 'g', 'i', 'n', 'z']
d=sorted(list(a))
>>> d
['a', 'b', 'e', 'f', 'g', 'i', 'n', 'z']

7.4 union合并集合

>>> a={'a','b','c','d','f'}
>>> b={'g','h','i','j','k'}
>>> c=a.union(b)
>>> c
{'g', 'f', 'a', 'h', 'k', 'c', 'b', 'd', 'i', 'j'}
>>> name="fangzebin"
>>> name
'fangzebin'
>>> a=set(name)
>>> a
{'g', 'n', 'f', 'a', 'z', 'b', 'e', 'i'}
>>> c=a.union(b)
>>> c
{'g', 'n', 'f', 'a', 'z', 'h', 'k', 'b', 'e', 'i', 'j'}

7.5、difference()区分不同元素:

>>> a={'a','b','c','d','e'}
>>> b={'a','c'}
>>> c=a.difference(b)
>>> c
{'b', 'e', 'd'}

7.6、intersection()报告共同对象

>>> d=a.intersection(b)
>>> d
{'a', 'c'}

参与贡献

  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request

特技

  1. 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
  2. Gitee 官方博客 blog.gitee.com
  3. 你可以 https://gitee.com/explore 这个地址来了解 Gitee 上的优秀开源项目
  4. GVP 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
  5. Gitee 官方提供的使用手册 https://gitee.com/help
  6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 https://gitee.com/gitee-stars/

空文件

简介

本仓库用于存放学习Python语言的学习笔记 展开 收起
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/fang_se_bin/python-learning-notes.git
git@gitee.com:fang_se_bin/python-learning-notes.git
fang_se_bin
python-learning-notes
Python学习笔记
master

搜索帮助