网站性能检测评分
注:本网站页面html检测工具扫描网站中存在的基本问题,仅供参考。
python中的count
Python 列表(list) 推广视频课程
Python 列表指包括0个或者多个对象元素引用的有序序列。对象元素的数据类型可以不同。列表同样可以包含列表,类似多维数组1、列表创建及索引
2、列表(List )以及列表元素的增删改查
列表元素的增加有insert、append 、extend方法以及+=操作
insert(index,obj) index=增加元素的位置,obj=增加的对象 append(obj) obj=增加的对象,追加obj对象元素至末尾 extend(list) list=list类型对象,把list对象元素追加至末尾
列表的增加就是合并列表。用+操作符进行合并生成新的列表
AllList=[] AllList.insert(0,"江苏") AllList.append("淮安") AllList.extend(["CoderA",40]) AllList+=["CoderS",41] print(AllList) OtherList=["CoderW",43] AllList2=AllList+OtherList #列表组合新列表AllList2 print(AllList2)
输出的结果:
列表元素的删除有Pop方法与remove() 方法 列表的删除用del方法 pop(index):index=删除元素的位置 remove(obj):obj=删除元素的名称 del listobj : listobj =删除列表的名称
DelList=["Python CoderA","Python CoderN","Python CoderW","Python CoderS"] DelList.pop()#默认删除最后的元素 DelList.pop(2)#删除第三个元素 DelList.remove("Python CoderN")#删除指定字符串 print(DelList) delDelList
列表元素的修改 对元素通过索引index重新赋值即可
列表除了使用+合并新列表以外,也可以用 * 坼分 Address,*Address2=["江苏","苏州","无锡","常州"] 不带星号变量对应正常索引的值,剩余的坼分给带星号的变量并且作为列表保存。
列表元素的查找 具备查找功能的方法:in、not in、index、count in与not in:判断元素是否在列表中 index:返回元素在列表中初次出现的位置 count:返回元素的个数
Python基础学习之常用六大数据类型 推广视频课程
刚开始学习一门编程语言,除了了解运行环境与语言类型之外,最基本还是从该语言的基本数据类型开始学起。
Python六大常用数据类型:
int 整数 float 浮点数 str 字符串 list 列表 tuple 元组 dict 字典
讲解这些先说一下python中的变量与变量名。
变量其实本质上是一个具有特殊格式的内存,变量名则是指向这个内存的别名。python中的变量不需要声明,所有的变量必须赋值了才能使用。赋值的步骤:
a = 100
第一步:准备好值100第二部:准备好变量名a第三部:将值与名字进行关联
一、整数python将其他一些静态语言中的int、long,也就是整型和长整型合并为了一个。python中的int是边长的,也就是说可以存储无限大的整数,但是这是不现实的,因为没有这么多的内存够分配。整型不仅支持十进制,还支持二进制、八进制、十六进制。可以通过下面的方式来互相转换:
print(bin(20)) #转换二进制print(oct(20)) #转换八进制print(hex(20)) #转换十六进制
二、浮点型浮点数也就是小数,如22.1,44.2,也可以使用科学计数法,比如:1.22e8。python支持对整数和浮点数直接进行四则混合运算。整数运算结果仍然是整数,浮点数运算结果仍然是浮点数,但整数和浮点数混合运算的结果就变成浮点数了。
a = 1b = 1.1print(type(a+b)) #
三、字符串字符串在任何编程语言中都是最常用的数据类型。字符串的创建很简单,也是上面所说的三步,但是要加上单引号或者双引号。
a = "hello python"
也可以使用 “”" 创建多行字符串:
a = """ hello python"""
字符串可以通过下面方式进行截取或者连接:
print (str[0:4]) 输出第一个到倒数第四个的所有字符 print (str[0]) 输出单字符 第1个字符print (str[3:]) 输出从第四个开始之后的所有字符print (str * 2) 输出字符串两次print (str + "bbbb") 连接字符串
字符串常用函数:str.strip() 消除字符串s左右两边的空白字符(包括’\t’,’\n’,’\r’,’’)len(str) 获取字符串长度str.upper() 转换为大写str.lower() 转换为小写str.title() 每个单词首字母大写str.capitalize() 首字母大写字符串翻转:
a = 'abcde'print(a[::-1])
字符串分割:
a = 'hello,python'print(a.split(',')) #['hello', 'python'] 返回一个列表
相对应的还有一个将列表元素连接成字符串:
a = ['hello', 'python']str = '-'print(str.join(a)) # hello-python
四、列表列表的写法是一个方括号内的值用逗号分隔。比如上面的[‘hello’, ‘python’]。列表的数据项不需要具有相同的类型,列表中的每个元素都分配一个数字索引,第一个索引是0,第二个索引是1,依此类推。访问列表中的值可以通过下面的方式:
list1 = [1, 2, 3, 4, 5, 6]print(list1[2])
同样可以通过索引截取
print ("list1[2:5]: ", list1[2:5])
列表常用操作:list1.append(‘7’) 追加一个元素在末尾,每次只能添加一个len(list1) 返回列表元素个数max(list1) 返回列表元素最大值min(list1) 返回列表元素最小值list1.count(obj) 统计某个元素在列表中出现的次数list1.index(obj) 从列表中找出某个值第一个匹配项的索引位置list1.reverse() 反向列表中元素list1.clear() 清空列表list1.extend(seq) 在列表末尾一次性追加另一个序列中的多个值,也就是扩充了列表 append与extend的区别:
A = ['a', 'b', 'c']A.append(['d', 'e'])print(A) # ['a', 'b', 'c', ['d', 'e']]B = ['a', 'b', 'c']B.extend(['d', 'e'])print(B) # ['a', 'b', 'c', 'd', 'e']
extend方法只能接收list类型,它是把这个列表中的每个元素添加到原list中。append可以接收任意类型,追加到原list的末尾。
五、元组元组的创建也很简单,和list类似,只是把’[]‘换成了’()’。
tup1 = ('hello', 'python')
元组中只有一个元素的时候要注意:
tup2 = (10)tup3 = ('a')print(type(tup2)) #
因为这样会被解释器当做运算符,所以正确的方法是在第一个元素后面添加逗号。
tup4 = ('a',)print(type(tup4)) #
元组同样可以使用下标索引来访问元组中的值:
tup5 = ('hello', 'python', 'hello', 'word')print(tup5[1]) #pythonprint(tup5[1:3]) #('python', 'hello')
注意:元组是不可以被修改的。
tup6 = ('hello', 'python', 'hello', 'word')tup6[2] = 'aaa'
上面会出现一个异常: TypeError: ‘tuple’ object does not support item assignment.但是元组中如果包含了一个列表,那么这个列表是可以被修改的。
tup7 = ('hello', 'python', 'hello', 'word', ['aa', 'bb', 'cc'])tup7[-1][1] = 'ddd'print(tup7) # ('hello', 'python', 'hello', 'word', ['aa', 'ddd', 'cc'])
元组运算符:len(tup) 计算元素个数tup1 + tup2 连接生成新元组tup * 4 元组复制num in tup 元素是否存在,返回True/False
六、字典python中的字典就是key,value的形式。使用大括号包含起来。字典中的成员的键是唯一的,如果出现多个同名的键,那么写在后面覆盖前面的值。形式如下:
dict1 = {'a' : 1, 'b' : 2}
字典的常用操作最基本的也就是增删改查:获取:直接通过键来获取。
dict['b'] # 2
dict.keys() 获取字典中所有的键dict.values() 获取字典中的所有的值增加:
dict1['c'] = 3 #{'a': 1, 'b': 2, 'c': 3} #如果键存在则更新对应的值
修改:直接给键进行再次赋值就可以修改键对应的值了。如果键不存在,则变成添加成员。还可以通过:
dict1.update({"a":"11"})dict1.setdefault("a", "222") # 已存在的键则修改无效dict1.setdefault("d","222") # 不存在的话则创建dict1.setdefault("e") # 没有设置值为None
删除:使用pop删除指定键对应的成员,同时返回该值
print(dict1) # {'a': '11', 'b': 2, 'c': 3, 'd': '222', 'e': None}print(dict1.pop("a")) # aprint(dict1) # {'b': 2, 'c': 3, 'd': '222', 'e': None}#在不设置默认值的情况下,使用pop删除不存在的键,会报错。print(dict1.pop("f")) # 报错 KeyError: 'f'
如果设置了默认值, print(dict1.pop(“f”, None)),则不会报错,返回这个默认值。判断是否删除成功可以通过下面方式来判断:
if dict1.pop("f", None) == None: print('键不存在')else: print('删除成功')
以上则是python中最基本的数据类型以及用法,当然还有其他的数据类型,作者暂时只列举了这些。
更过python文章,关注作者哦!干货多多!!
六、python中字符串的常用方法 推广视频课程
1.capitalize()方法
s = 'jack and tom and jack''''capitalize() 方法:Return a capitalized version of the string. ---> 返回字符串的大写版本More specifically, make the first character have upper case and the rest lower case. --->更具体的说,使第一个字符具有大写字母,其余字母为小写字母'''print(s.capitalize())
2.title()方法
'''title() 方法:Return a version of the string where each word is titlecased.--> 返回一个字符串,其中每个单词的首字母大写More specifically, words start with uppercased characters and all remainingcased characters have lower case. -->更具体的说,每个单词以大写字母开始,其余都是小写字母'''print('abc*abc'.title())
3.center()方法
'''center() 方法:Return a centered string of length width.-->返回长度为宽度的居中字符串。Padding is done using the specified fill character (default is a space).-->填充是使用指定的填充字符完成的(默认为空格)'''print('abc'.center(9,'-'))
4.count()方法
'''count() 方法:S.count(sub[, start[, end]]) -> intReturn the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.查找子字符串 sub 在字符串中出现的次数,可选参数,开始 和 结束 可理解为切片'''print(s.count('and',1,3))
5.endswith()方法
'''endswith() 方法:S.endswith(suffix[, start[, end]]) -> boolReturn True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.如果S以指定后缀结尾,则返回True,否则返回False。可以指定起始和结束位置,后缀也可以是要尝试的字符串元组。 '''print('tom and jack'.endswith('jack',10))
6.find()方法
'''find() 方法:S.find(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.在字符串 S 中查找子字符串sub,如果找到,返回子字符串sub在字符串s中首次出现的索引,没有找到返回 -1参数start 和 end 可以理解为切片'''print('hello world python'.find('world',6))print('hello world python'.find('world',6))
7.format()方法:
'''format() 方法:S.format(*args, **kwargs) -> strReturn a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').使用来自args和kwargs的替换返回S的格式化版本。替换用大括号(“{”和“}”)标识。'''s_format = '我的名字叫{},我的年龄是{}'.format('jack',19)print(s_format)s_format = '我的名字叫{name},我的年龄是{age},我的名字叫{name}'.format(name='jack',age=19)print(s_format)s_format = '我的名字叫{0},我的年龄是{1},我的名字叫{0}'.format('jack',19)print(s_format)
8.index()方法
'''index() 方法:S.index(sub[, start[, end]]) -> intReturn the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Raises ValueError when the substring is not found.在字符串 s 中查找 子字符串 sub,在指定位置 start 和 end 之间查找,参数 start 和 end 可理解为切片,如果没有找到,则会抛出 ValueError错误。找到,返回最先出现的索引'''s_index = 'return the lowest index in S where'print(s_index.index('the'))
9.lower()方法:
'''lower() 方法:Return a copy of the string converted to lowercase.返回转换为小写的字符串副本。将字符串中的所有字符转换成小写字母'''print('AbCdddEfgjKH'.lower())
10.lstrip()方法:
'''lstrip() 方法:Return a copy of the string with leading whitespace removed. 返回一个删除前导(左侧)空白字符的副本。 If chars is given and not None, remove characters in chars instead. 如果这个字符chars是给定的,而不是None,则删除指定的字符,而不是空白字符'''print(' abdde'.lstrip())print('***abdcd'.lstrip('*'))
11.replace()方法:
'''replace() 方法:Return a copy with all occurrences of substring old replaced by new.返回一个字符串的副本,使用新的子字符串替换旧的子字符串count Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. 替换的次数,默认为-1 ,表示替换所有的子字符串If the optional argument count is given, only the first count occurrences are replaced.如果参数count给定的指定次数。则替换指定的次数'''print('abcabdabcabc'.replace('a','A',3))
12.split()方法:
'''split()方法:Return a list of the words in the string, using sep as the delimiter string. 将字符串使用指定分隔符进行拆分,并返回一个list sep 用作拆分的分隔符 The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. 参数为空,默认使用空白字符进行拆分,返回的结果中抛弃空白字符 maxsplit 表示要执行的最大拆分 Maximum number of splits to do. -1 (the default value) means no limit. 表示要执行的最大拆分次数,-1 默认值,表示没有限制'''print('Maximum number of splits to do'.split())
13.rstrip()方法
'''rstrip() 方法:去掉字符串右边的字符,默认去掉空白字符,同 lstrip()方法'''print('abc***'.rstrip('*'))'''startswith() 方法: S.startswith(prefix[, start[, end]]) -> boolReturn True if S starts with the specified prefix, False otherwise.With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. 如果以指定的字符串开头,则返回True,否则返回False. 同endswith()方法类似'''print('abc'.startswith('a'))
14.strip()方法
'''strip()方法: 同rstrip() 和 lstrip() 方法。去掉字符串首尾的空白字符,或者指定字符'''print('*%abc%'.strip('*%'))
15.upper()方法
'''upper()方法:Return a copy of the string converted to uppercase.将字符串中的所有字符转换成大写字母,并返回一个字符串副本 同lower()方法对应'''print('abcdaAKJFA'.upper())
中小学python教学案例:输入一串数字排列后最大值 最小值 公司视频课程
问题:输入一串数字,输出经过排列后的最大值、最小值及相同位数的最小值 运用
python源代码(已验证)
str=input("输入一个数字")s=sorted(list(str))max=eval("".join(s[::-1]))
count0=s.count("0")min=eval("".join(s[count0:]))min1=s[:count0+1][::-1]+s[count0+1:]min1=eval("".join(min1))print("最大值:{},最小值:{},相同位数最小值:{}".format(max,min,min1))
知识点:
1、列表的排序
2、列表的项查找
3、列表的切片
4、列表和字符串的转换
"""
str = input("输入一个数字")
#把数字字符串str转成列表s,并进行排序,默认为升序
s = sorted(list(str))
#把列表倒序转成字符串,并用eval转换成数值即为最大值max
max = eval("".join(s[::-1]))
#查找列表中“0”的个数,赋值给count0
count0 = s.count("0")
#把“0”后面的列表转换成字符串,并用eval转换成数值即为最小值min
min = eval("".join(s[count0:]))
#把列表s中前面count0个项进行倒序加上后面项,解决第一项为0的问题
min1 = s[:count0+1][::-1]+s[count0+1:]
#同理列表转字符串再转数值,即为相同位数的最小值min1
min1 = eval("".join(min1))
print("最大值:{},最小值:{},相同位数最小值:{}".format(max,min,min1))
Pyhton源代码:
str=input("输入一个数字")s=sorted(list(str))max=eval("".join(s[::-1]))
count0=s.count("0")min=eval("".join(s[count0:]))min1=s[:count0+1][::-1]+s[count0+1:]min1=eval("".join(min1))print("最大值:{},最小值:{},相同位数最小值:{}".format(max,min,min1))
运行结果
输入一个数字:1342
最大值:4321,最小值:1234,相同位数最小值1234
输入一个数字:1053
最大值:5310,最小值:135,相同位数最小值1035
五、Python中的列表(list) 推广视频课程
列表是在Python中是一组数据的集合 如:
li = ['jack','tom','jim']
列表中的数据类型也可以不同 如:
li = ['jack',123,'tom',89]
列表中也可以嵌套列表 如:
li= ['jack',123,['hello','python',89],'中国']
定义一个列表
li= ['jack',123,'hello','python',89,'中国','你好']
读取列表中的元素,可以使用下标来读取,下标从 0 开始,但是如果超出了列表的长度,就会报错:IndexError: list index out of range
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[0])
print(li[2][0])
如果要取出最后一个元素的下标为 -1,倒数第二个元素为 -2 从后往前,依次类推
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[-1])
print(li[-2])
切片也支持在列表中的使用 返回一个列表,如:
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[0:3])
也可以设置步长,倒着取
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[::-2])
读取列表的长度,可以使用len()函数
li= ['jack',123,'hello','python',89,'中国','你好']
print(len(li))
在列表中添加元素 append() 方法,默认在列表的末尾添加一个元素
li= ['jack',123,'hello','python',89,'中国','你好']
li.append('添加的元素')
print(li)
在列表的指定位置添加元素,insert()方法
li= ['jack',123,'hello','python',89,'中国','你好']
li.insert(2,'alex')
li= ['jack',123,'hello','python',89,'中国','你好']
li.insert(2,'alex')
print(li)
删除元素:pop()方法: 默认删除列表中的最后一个元素,并返回该元素
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.pop())
删除指定元素pop() 方法:可添加参数,删除指定下标的元素,并返回该元素
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.pop(0))
清空列表 clear() 方法 返回 None
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.clear())
remove() 方法:删除指定元素
li= ['jack',123,'hello','python',89,'中国','你好']
li.remove('jack')
print(li)
复制列表
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.copy())
count() 返回一个数据在列表中出现的次数
li= ['jack',123,'hello','python',89,'中国','你好','python']
print(li.count('python'))
extend() 方法 方法中的参数必须是一个iterable。
lis = ['1',2,3]
lis.extend('abc')
print(lis)
index()方法: 返回一个元素在列表中首次出现的位置,如果找到,返回下标,如果没有找到,则报错.
也可以指定起始和结束位置
lis = ['a','b','c','a']
print(lis.index('a',1))
revrese()方法,翻转列表
li= ['jack',123,'hello','python',89,'中国','你好','python']
li.reverse()
print(li)
sort() 排序
li = [1, 8, 0, 7, 76, 89]
li.sort()
print(li)
翻转排序
li = [1, 8, 0, 7, 76, 89]
li.sort(reverse= True)
print(li)
字符串和列表之间的转换 字符串变成列表 可以使用split()方法
s1 = 'a,b,c,d,e,f,h'
print(s1.split(','))
列表转换成字符串
l1 = ['a', 'b', 'c', 'd', 'e', 'f', 'h']
print(''.join(l1))
join 方法
s = 'abc'
print('-'.join(s))
五、Python中的列表(list) 企业视频课程
列表是在Python中是一组数据的集合 如:
li = ['jack','tom','jim']
列表中的数据类型也可以不同 如:
li = ['jack',123,'tom',89]
列表中也可以嵌套列表 如:
li= ['jack',123,['hello','python',89],'中国']
定义一个列表
li= ['jack',123,'hello','python',89,'中国','你好']
读取列表中的元素,可以使用下标来读取,下标从 0 开始,但是如果超出了列表的长度,就会报错:IndexError: list index out of range
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[0])
print(li[2][0])
如果要取出最后一个元素的下标为 -1,倒数第二个元素为 -2 从后往前,依次类推
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[-1])
print(li[-2])
切片也支持在列表中的使用 返回一个列表,如:
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[0:3])
也可以设置步长,倒着取
li= ['jack',123,'hello','python',89,'中国','你好']
print(li[::-2])
读取列表的长度,可以使用len()函数
li= ['jack',123,'hello','python',89,'中国','你好']
print(len(li))
在列表中添加元素 append() 方法,默认在列表的末尾添加一个元素
li= ['jack',123,'hello','python',89,'中国','你好']
li.append('添加的元素')
print(li)
在列表的指定位置添加元素,insert()方法
li= ['jack',123,'hello','python',89,'中国','你好']
li.insert(2,'alex')
li= ['jack',123,'hello','python',89,'中国','你好']
li.insert(2,'alex')
print(li)
删除元素:pop()方法: 默认删除列表中的最后一个元素,并返回该元素
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.pop())
删除指定元素pop() 方法:可添加参数,删除指定下标的元素,并返回该元素
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.pop(0))
清空列表 clear() 方法 返回 None
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.clear())
remove() 方法:删除指定元素
li= ['jack',123,'hello','python',89,'中国','你好']
li.remove('jack')
print(li)
复制列表
li= ['jack',123,'hello','python',89,'中国','你好']
print(li.copy())
count() 返回一个数据在列表中出现的次数
li= ['jack',123,'hello','python',89,'中国','你好','python']
print(li.count('python'))
extend() 方法 方法中的参数必须是一个iterable。
lis = ['1',2,3]
lis.extend('abc')
print(lis)
index()方法: 返回一个元素在列表中首次出现的位置,如果找到,返回下标,如果没有找到,则报错.
也可以指定起始和结束位置
lis = ['a','b','c','a']
print(lis.index('a',1))
revrese()方法,翻转列表
li= ['jack',123,'hello','python',89,'中国','你好','python']
li.reverse()
print(li)
sort() 排序
li = [1, 8, 0, 7, 76, 89]
li.sort()
print(li)
翻转排序
li = [1, 8, 0, 7, 76, 89]
li.sort(reverse= True)
print(li)
字符串和列表之间的转换 字符串变成列表 可以使用split()方法
s1 = 'a,b,c,d,e,f,h'
print(s1.split(','))
列表转换成字符串
l1 = ['a', 'b', 'c', 'd', 'e', 'f', 'h']
print(''.join(l1))
join 方法
s = 'abc'
print('-'.join(s))