Python学习---基础篇

 ###打开文件并打印:

1 #!/usr/bin/python3
2 
3 f = open('F://myproject/test.txt', encoding='utf-8',mode='r')
4 content = f.read()
5 print(content)
6 f.close()

###使用os模块的walk() 遍历文件目录:

 1 #!/usr/bin/python3
 2 import os
 3 import os.path
 4 
 5 dir = "f:/project/"                         
 6 
 7 for dirpath,dirnames,filenames in os.walk(dir):    
 8     for dirname in  dirnames:
 9         print("dirpath is:" + dirpath)
10         print("dirname is:" + dirname)
11     
12     for filename in filenames:                        
13         print ("dirpath is:" + dirpath)
14         print ("filename is:" + filename)
15         print ("the full name of the file is:" + os.path.join(dirpath,filename))

遍历目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】

### 冒泡排序

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 
 4 def bubbleSort(nums):
 5     for i in range(len(nums)-1):
 6         for j in range(len(nums)-i-1):
 7             if nums[j] > nums[j+1]:
 8                 nums[j], nums[j+1] = nums[j+1], nums[j]
 9     return nums
10 nums = [9,2,45,67,32,7,87,28,6]
11 print(bubbleSort(nums))

 range() 函数可创建一个整数列表,range(1,10)表示从[123456789]

### 插入排序

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 
 4 def insert_sort(lists):
 5     count = len(lists)
 6     for i in range(1, count):
 7         key = lists[i]
 8         j = i - 1
 9         while j >= 0:
10             if lists[j] > key:
11                 lists[j + 1] = lists[j]
12                 lists[j] = key
13             j -= 1
14     return lists

### 选择排序

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 
 4 def select_sort(lists):
 5     count = len(lists)
 6     for i in range(0, count):
 7         cnt = i
 8         for j in range(i + 1, count):
 9             if lists[cnt] > lists[j]:
10                 cnt = j
11         lists[cnt], lists[i] = lists[i], lists[cnt]
12     return lists

### 输出乘法表

1  print('
'.join(['	'.join(['%d * %d = %d'%(y,x,x*y) for y in range(1,x+1)])for x in range(1,10)]))

 join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。‘ ’.join(parameter) 表示用' '连接元素序列parameter中的各元素

### 删除列表重复元素

1  list = [1,1,2,3,6,8,9,6,6,7,8]
2  set(list)

### 反转字符串

1 str = "string"
2 str[::-1]

### 切割字符串

 1 #!/usr/bin/python3
 2 # coding:utf-8
 3 
 4 str="1:a$2:b$3:c$4:d"
 5 str_list=str.split('$')
 6 res={}
 7 for l in str_list:
 8     key,value=l.split(':')
 9     res[key]=value
10 print(res)
原文地址:https://www.cnblogs.com/tyche116/p/8709209.html