赞
踩
- a_list=[] #创建一个空的a_list列表
- for i in range(1,2021):
- a_list.append(i) #将1—2020个数字添加进a_list列表
- b_str=str(a_list) #把列表转化成为字符串并赋值给b——str
- print(b_str.count("2"))#使用count方法返回2在b_str中出现的次数
-
'运行
代码中的b_str.cout("2"),相当于是查找的是2这个字符串,所以要加引号(“”)
关于方法:
“方法”在编程中是一个专有名词
-“方法”特指<a>.<b>()风格中的函数<b>()
-方法本身也是函数,但与<a>有关,<a>.<b>()风格使用
-字符串及变量也是<a>,也存在一些方法。
一些以方法形式提供的字符串处理功能
- with open('2020.txt','r') as f:#把2020.txt的值赋给了f
- content = f.read().split('\n') #用split分割读取的文件内容中的字符
- m = len(content)#m表示行数
- n = len(content[0])#表示列数
- count = 0
- #从左往右边找
- for i in range(m):
- for j in range(n-3):#确定一个,-3可以防止越界
- if content[i][j] == '2' and content[i][j+1] == '0' and content[i][j+2] == '2' and content[i][j+3] == '0':
- count += 1
- #从上到下找
- for j in range(n):
- for i in range(m-3):
- if content[i][j] == '2' and content[i+1][j] == '0' and content[i+2][j] == '2' and content[i+3][j] == '0':
- count += 1
- #从左上往左下
- for i in range(m-3):
- for j in range(n-3):
- if content[i][j] == '2' and content[i+1][j+1] == '0' and content[i+2][j+2] == '2' and content[i+3][j+3] == '0':
- count += 1
- print(count)
- 使用Python内置函数
open()
可以打开一个文件,并返回一个文件对象。在文件对象上可以调用read()
方法读取文件内容。- 其中,
2020
.txt
是要读取的文件名,r
代表读取模式。使用with
语句可以保证文件在读取完成后自动关闭,content
是读取到的文件内容。open()
函数还有其他的参数可以进行设置,比如设置读取模式、设置字符编码等。例如,如果要写入文件,可以使用w
模式,如果要追加内容,可以使用a
模式。使用open()
函数读取文件时,建议使用with
语句,这样可以更好地管理文件的打开和关闭。- 关于二维数组(图片来自网络,我截屏的方便理解。不知道怎么把自己的水印去掉,sorry!)
- 闰年 四年一闰,百年不闰,四百年再闰。例如:2000年是闰年,2100年则是平年。(year % 2 == 0 and year % 100 != 0 )or year % 400 == 0 闰年比平年多一天
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。