python zip dict函数

1.zip函数

zip函数可以接受多个参数,返回的结果是列表,列表中的每一个元素是元组的数据类型,下面我们通过几个例子来学习zip函数的用法

1)

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]
zip(list1,list2,list3)

最后的返回的结果是:

[(1,4,7),(2,5,8),(3,6,9)]

2)

list1 = [1,2,3]
list2 = [4,5,6,7]
zip(list1,list2)

返回的结果是

[(1,4),(2,5),(3,6)]

上面的这个例子我们可以发现zip函数在字长上的处理

3)

list1 = [1,2,3]
zip(list1)

最后的返回结果是

[(1,),(2,),(3,)]

4)

zip()

最后的返回结果是[]

2.dict函数

dict函数用来快速构造字典,我们可以通过向dict函数传递不同的参数一不同的方式来创建字典,下面我们来了解一下几种常见的构造字典的方式

1)创建空字典

a = dict()#创建空字典
print(a)

结果

{}

2)传入关键字

b = dict(a=1,b=2,c=3)
print(b)

得到的结果是:

{"a":1,"b":2,"c":3}

3)传入一个字典:

c = dict({'three': 3, 'four': 4})
print(c)

结果

{'four': 4, 'three': 3}

4)传入可迭代对象

d = dict([('one', 1), ('two', 2), ('three', 3)])
print(d)

得到的结果是

{'three': 3, 'two': 2, 'one': 1}

猜你喜欢

转载自www.cnblogs.com/niusha/p/10385574.html
今日推荐