题目地址:https://leetcode.com/problems/flipping-an-image/description/
大意:两次反转二元矩阵,第一次将子元素序列倒置,第二次将子元素的子元素0变1,1变0。所以两层for循环可以搞定。
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
rlist = []
for item in A:
new_item = item[::-1]
for n,element in enumerate(new_item):
if element == 0:
new_item[n] = 1
else:
new_item[n] = 0
rlist.append(new_item)
return rlist
a = Solution()
print(a.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]]))
print(a.flipAndInvertImage([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]))
知识点1:这里翻转用了
list[::-1]
的方法,具体定义用用法如下图。
a[firstIndexInclusive:endIndexExclusive:Step]
>>> a = range(20)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[7:] #seventh term and forward
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[:11] #everything before the 11th term
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[::2] # even indexed terms. 0th, 2nd, etc
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> a[4:17]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> a[4:17:2]
[4, 6, 8, 10, 12, 14, 16]
>>> a[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> a[19:4:-5]
[19, 14, 9]
>>> a[1:4] = [100, 200, 300] #you can assign to slices too
>>> a
[0, 100, 200, 300, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
注意:本来想用list.reverse()
这种方法的,但是这个是直接改变list,不返回list,所以不能用list2 = list.reverse()
这种方法。
知识点2:
enumerate()
给了list一个索引值,很常见的写法。