python-enumerate()函数

0.摘要

python中的enumerate()函数为枚举函数,能够将数字可迭代变量中的元素快速打包成一个元组。

1.功能介绍

enumerate(iterable[, start]) -> iterator for index, value of iterable

iterable:可迭代对象,列表、numpy.array、元组、字符串等。

start:数字编号起点,默认为0

返回值:迭代器。输出需要先转为list。

a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
t = list(enumerate(a, 97))
print(t)
# [(97, 'a'), (98, 'b'), (99, 'c'), (100, 'd'), (101, 'e'), (102, 'f'), (103, 'g'), (104, 'h'), (105, 'i')]

2.应用

比如快速打印清单。

commodities = ['oil', 'salt', 'sauce', 'vinegar', 'tea']
print("Num"," | ","commodity")
print("- - - - - - - - - ")
for i, commodity in enumerate(commodities):
    commodity = commodity.rjust(10)
    print(i, "   | ",commodity)

猜你喜欢

转载自blog.csdn.net/qq_17753903/article/details/89501458
今日推荐