Python打卡Day20

Question 80

Question

Please write a program to print the list after removing even numbers in [5,6,77,45,22,12,24].


Hints

Use list comprehension to delete a bunch of element from a list.


Main author's Solution: Python 2

1li = [5,6,77,45,22,12,24]
2li = [x for x in li if x%2!=0]
3print li

My Solution: Python 3

1def isEven(n):
2    return n%2!=0
3
4li = [5,6,77,45,22,12,24]
5lst = list(filter(isEven,li))
6print(lst)

OR

1li = [5,6,77,45,22,12,24]
2lst = list(filter(lambda n:n%2!=0,li))
3print(lst)

Question 81

Question

By using list comprehension, please write a program to print the list after removing numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].


Hints

Use list comprehension to delete a bunch of element from a list.


Main author's Solution: Python 2

1li = [12,24,35,70,88,120,155]
2li = [x for x in li if x%5!=0 and x%7!=0]
3print li

My Solution: Python 3

1li = [12,24,35,70,88,120,155]
2li = [x for x in li if x % 35!=0]
3print(li)

Question 82

Question

By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].


Hints

Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple.


Main author's Solution: Python 2

1
2li = [12,24,35,70,88,120,155]
3li = [x for (i,x) in enumerate(li) if i%2!=0]
4print li

My Solution: Python 3

1li = [12,24,35,70,88,120,155]
2li = [li[i] for i in range(len(li)) if i%2 != 0]
3print(li)

Question 83

Question

By using list comprehension, please write a program to print the list after removing the 2nd - 4th numbers in [12,24,35,70,88,120,155].


Hints

Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple.


Main author's Solution: Python 2

1
2li = [12,24,35,70,88,120,155]
3li = [x for (i,x) in enumerate(li) if i<3 or 4<i]
4print li

My Solution: Python 3

1#to be written
2li = [12,24,35,70,88,120,155]
3li = [li[i] for i in range(len(li)) if i<3 or 4<i]
4print(li)

Question 84

Question

By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.


Hints

Use list comprehension to make an array.


Solution:

1array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
2print array

go to previous day

go to next day

Discussion