python学习 第二篇 排序

简介:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#coding:utf-8
#用户输入名字和分数,并保存到list。如果输入为空,打印并结束循环。并算出平均值
list1 = []
count = 0
num = 0
while  True :
  x = raw_input ( 'please input your name:' )
  y = raw_input ( 'please input your grade:' )
  if  y.isdigit()  and  x.isalpha():
     list1.append( int (y))
     list1.append( str (x))
     count + = 1
     num = int (num) + int (y)
  elif  len (x) = = 0  or  len (y) = = 0 :
     avg = num / count
     print  list1
     break
  else :
     print  'input is error'
print  '平均值是 %s'  % (avg)
 
#list最重要的一个特点:有序。 通过索引获取值   列表[索引]
#索引前面是从0开始,后面是从-1 开始
 
#list 是一个内置函数,不要以它命名
#arr = ['C','python','js','css','html','node']
#print arr[-6]
#arr1=list('python')
#print arr1
#for i in ['wd','pc','wn']:
#   print i
#print 'wd' in ['wd','pc'] 
#print 'wn' in ['wd','pc'] 
arr = [ 1 , 2 , 3 , 4 , 5 , 6 ]
#print len(arr)
#print max(arr)
#print min(arr)
#len(列表)返回列表的长度 min 最小值,max最大值
del  arr[ 3 ]
print  arr
#修改 根据索引找到值,并重新赋值
arr[ 0 ] = 'hello'
print  arr
 
 
#排序  编程世界的游戏规则
#    根据索引找到值
#    值可以比大小
#    值可以交换位置
#冒泡排序
#  挨个对比,如果 一个元素比右边的大,交换位置
arr = [ 3 , 4 , 8 , 9 , 10 , 6 , 5 , 7 ]
length = len (arr)
for  in  range (length - 1 ):
     print  '*' * 20
     print  i
     for  in  range (length - i - 1 ):
         if  arr[j]>arr[j + 1 ]:
             arr[j],arr[j + 1 ] = arr[j + 1 ],arr[j]
             print  'list is %s' % (arr)
print  arr
1
2
3
4
5
6
7
8
9
10
#coding=UTF-8
#插入排序
#插入排序(Insertion Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入
array  =  [ 3 , 1 , 4 , 2 , 5 , 7 , 6 ]
length  =  len (array)
for  in  range (length - 1 ):
    for  in  range (i + 1 ,length):
         if  array[i]>array[j]:
                 array[i],array[j] = array[j],array[i]
print  array




本文转自 shouhou2581314 51CTO博客,原文链接:http://blog.51cto.com/thedream/1825648,如需转载请自行联系原作者
相关文章
|
8天前
|
Python
python函数的参数学习
学习Python函数参数涉及五个方面:1) 位置参数按顺序传递,如`func(1, 2, 3)`;2) 关键字参数通过名称传值,如`func(a=1, b=2, c=3)`;3) 默认参数设定默认值,如`func(a, b, c=0)`;4) 可变参数用*和**接收任意数量的位置和关键字参数,如`func(1, 2, 3, a=4, b=5, c=6)`;5) 参数组合结合不同类型的参数,如`func(1, 2, 3, a=4, b=5, c=6)`。
13 1
|
12天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
17 1
|
4天前
|
Python
python学习3-选择结构、bool值、pass语句
python学习3-选择结构、bool值、pass语句
|
2天前
|
机器学习/深度学习 算法 Python
使用Python实现集成学习算法:Bagging与Boosting
使用Python实现集成学习算法:Bagging与Boosting
15 0
|
4天前
|
Python
python学习14-模块与包
python学习14-模块与包
|
4天前
|
Python
python学习12-类对象和实例对象
python学习12-类对象和实例对象
|
4天前
|
数据采集 Python
python学习9-字符串
python学习9-字符串
|
4天前
|
Python
python学习10-函数
python学习10-函数
|
4天前
|
存储 索引 Python
python学习7-元组
python学习7-元组
|
4天前
|
Python
python学习8-集合
python学习8-集合

热门文章

最新文章