美文网首页
Python enumerate() 函数和zip()函数

Python enumerate() 函数和zip()函数

作者: 小飞船1号 | 来源:发表于2020-06-09 11:30 被阅读0次
  1. 语法:enumerate(sequence, [start=0])
  2. 参数:
  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。
  1. 返回值:返回 enumerate(枚举) 对象
#eg1
def get_enum():
    seq=["w","r","t","y"]
    print(list(enumerate(seq)))
    print(list(enumerate(seq,start=1)))
    for i ,item in enumerate(seq):
        print(f"{i},{item}")

print(get_enum())
#eg2:组成字典
widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
temp_dict={f"{chr(i+97)}":widths[i] for i ,v in enumerate(widths)}
print(temp_dict)
[(0, 'w'), (1, 'r'), (2, 't'), (3, 'y')]

[(1, 'w'), (2, 'r'), (3, 't'), (4, 'y')]

0,w
1,r
2,t
3,y

{'a': 4, 'b': 10, 'c': 10, 'd': 10, 'e': 10, 'f': 10, 'g': 10, 'h': 10, 'i': 10, 'j': 10, 'k': 10, 'l': 10, 'm': 10, 'n': 10, 'o': 10, 'p': 10, 'q': 10, 'r': 10, 's': 10, 't': 10, 'u': 10, 'v': 10, 'w': 10, 'x': 10, 'y': 10, 'z': 10}

zip() 函数

用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

M=["t11111","t2222","t3333","t4444","t55555"]
for page,t in zip(range(2,18),M):
    url ="https://tx_news?currentPage={}&cHash={}".format(page,t)
    print(url)

M=["t11111","t2222","t3333","t4444","t55555"]
Q=["ww","ee","rr","66","yy","uu"]
for page,t in zip(Q,M):
    url ="https://tx_news?currentPage={}&cHash={}".format(page,t)
    print(url)
#zip组成字典
widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
map_dic = dict(zip('abcdefghijklmnopqrstuvwxyz',widths))
print(map_dic)
https://tx_news?currentPage=2&cHash=t11111
https://tx_news?currentPage=3&cHash=t2222
https://tx_news?currentPage=4&cHash=t3333
https://tx_news?currentPage=5&cHash=t4444
https://tx_news?currentPage=6&cHash=t55555

https://tx_news?currentPage=ww&cHash=t11111
https://tx_news?currentPage=ee&cHash=t2222
https://tx_news?currentPage=rr&cHash=t3333
https://tx_news?currentPage=66&cHash=t4444
https://tx_news?currentPage=yy&cHash=t55555

{'a': 4, 'b': 10, 'c': 10, 'd': 10, 'e': 10, 'f': 10, 'g': 10, 'h': 10, 'i': 10, 'j': 10, 'k': 10, 'l': 10, 'm': 10, 'n': 10, 'o': 10, 'p': 10, 'q': 10, 'r': 10, 's': 10, 't': 10, 'u': 10, 'v': 10, 'w': 10, 'x': 10, 'y': 10, 'z': 10}

相关文章

网友评论

      本文标题:Python enumerate() 函数和zip()函数

      本文链接:https://www.haomeiwen.com/subject/abtgzhtx.html