Python小练习


1. 下列代码输出结果

num = [108, 20, 78, 15, 8, 2, 5, 3, 11]
result = [x for x in num[::2] if x%2 == 0]
print result

list第二个冒号后显示的是步长。 for循环后得出的结果x

2. Python对数字由小到大排序

num = [33, 56, 10, 3, 8, 17, 101, 88, 45, 99]

for i in range(0, len(num)):
    for j in range (0, i):
        if num[i] <= num[j]:
            num[i], num[j] = num[j], num[i]

print num

3. Python如何执行一个shell命令

4. Python变量复制

import copy


a = [1, 2, 3, 4, ['a', 'b']]

b = a
c = copy.copy(a)
d = copy.deepcopy(a)
a.append(5)
a[4].append('c')

print 'a = ', a
print 'b = ', b
print 'c = ', c
print 'd = ', d

输出结果

a =  [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b =  [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c =  [1, 2, 3, 4, ['a', 'b', 'c']]
d =  [1, 2, 3, 4, ['a', 'b']]

Last updated