在平时的编程解决问题的过程有时候需要对列表或者元祖里面的元素一一对应,这个时候就可以使用python中的zip函数进行解决,zip函数一个很重要的作用是可以将多个有关系的列表中的元素进行一一对应,这样在排序的过程中可以保持元素相对位置不变,菜鸟教程中对zip函数的描述如下:
① zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
② 我们可以使用 list() 转换来输出列表。
③ 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表
④ 可以使用zip函数来同时遍历长度相同的两个字典
下面是简单的一些例子:
if __name__ == '__main__':
# zip函数
a = ["a", "b", "c", "d", "e", "f"]
b = [1, 2, 3, 4, 5, 6]
c = [0, 1, 2, 3, 4, 5]
# zip函数的参数为可以迭代的对象
print(type(zip(a, b, c)))
for i, j, k in zip(a, b, c):
print(i, j, k)
# 当迭代的对象长度不一样的时候那么以长度较短的列表为准
a = [1, 2, 3]
b = [4, 5, 6, 7, 8]
for i, j in zip(a, b):
print(i, j)
if __name__ == '__main__':
a = [1, 2, 3]
b = ["a", "b", "c"]
zipped = zip(a, b)
print(list(zipped))
import collections
from typing import List
class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
row, col = collections.defaultdict(int), collections.defaultdict(int)
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == 1:
row[i] += 1
col[j] += 1
res = 0
for value1, value2 in zip(row.values(), col.values()):
if value1 == 1 and value2 == 1: res += 1
return res
if __name__ == '__main__':
print(Solution().numSpecial([[1, 0, 0],
[0, 0, 1],
[1, 0, 0]]))