05 python列表 练习题(排序输出-复制列表-完成数-逗号分隔列表-反向输出列表-判断某年某月某日是一年中的第几天)

(1)(例5)输入3个整数,将他们由小到大输出(列表)

list = []
for i in range(3):
    x = int(input("请输入整数:"))
    list.append(x)
list.sort()
print(list)

(2)例7题目:将一个列表的数据复制到另一个列表中

#!/usr/bin/python # -*- coding: UTF-8 -*- 
a = [1, 2, 3] 
b = a[:] 
print b

3)练习19题目:一个数如果恰好等于它的因子之和,这个数就称为”完数”。例如6=1+2+3.编程找出1000以内的所有完数。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from sys import stdout
for j in range(2,1001):
k = []
n = -1
s = j
for i in range(1,j):
        if j % i == 0:
            n += 1
            s -= i
            k.append(i)
if s == 0:
    print j
    for i in range(n):
        stdout.write(str(k[i]))
        stdout.write(' ')
    print k[n]

(4)练习33:按逗号分隔列表。
#!/usr/bin/python
# -- coding: UTF-8 --

L = [1,2,3,4,5]
s1 = ','.join(str(n) for n in L)
print s1

(5)练习32题目:按相反的顺序输出列表的值。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

a = ['one', 'two', 'three']
for i in a[::-1]:
print  

(6)(例4)题目:输入某年某月某日,判断这一天是这一年的第几天?

#!/usr/bin/python
# -*- coding: UTF-8 -*-

year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
*#months是一个列表,存储的是到当前月份之前所有月份的天数和*
months = [0,31,59,90,120,151,181,212,243,273,304,334]
*#判断输入的月份是否正确,1~12*
if 0 < month <= 12:
    sum = months[month - 1]
else:
    print 'data error'
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
#格式化输出
print ('it is the %dth day.' % sum) 

(7)打印杨辉三角形前十行
如下:

1  

1  1  

1  2  1  

1  3  3  1  

1  4  6  4  1  

1  5  10  10  5  1  

1  6  15  20  15  6  1  

1  7  21  35  35  21  7  1  

1  8  28  56  70  56  28  8  1  

1  9  36  84  126  126  84  36  9  1  

代码

a = []
for i in range(10):
a.append([])
for j in range(10):
    a[i].append(0)
#将所有列表值设0,否则会出现列表索引值错误

for i in range(10):
    a[i][0] = 1
    a[i][i] = 1
for i in range(2,10):
    for j in range(1,i+1):
        a[i][j] = a[i-1][j-1]+a[i-1][j]
for i in range(10):
    for j in range(i+1):
        print(a[i][j],' ', end="")
    print("\n")

你可能感兴趣的:(05 python列表 练习题(排序输出-复制列表-完成数-逗号分隔列表-反向输出列表-判断某年某月某日是一年中的第几天))