Python enumerate函数无法顺序遍历集合

您所在的位置:网站首页 pop函数用法python能用于集合么 Python enumerate函数无法顺序遍历集合

Python enumerate函数无法顺序遍历集合

2024-02-29 02:42| 来源: 网络整理| 查看: 265

今天使用Python中的enumerate函数,犯了一个很低级的错误,enumerate用于遍历如字符串,列表,元组中的变量,但是并不能顺序遍历字典中的变量,举个例子:

在Python中,单引号或者双引号('或")创建字符串,用中括号([])创建列表,用括号(())创建元组,用大括号({})创建字典,但是{}内没有键值的话,类型是集合。 元组与列表的作用差不多,不同之处在于元组的元素不能修改。

print('字符串:') myvar = 'Hello' for index,name in enumerate(myvar): print(index) print(name) print('列表:') mylist =['one','two','three','four'] for index,name in enumerate(mylist): print(index) print(name) print('元组:') mydict = ('one','two','three','four'); for index,name in enumerate(mydict): print(index) print(name) print('集合:') mydict = {'one','two','three','four'}; for index,name in enumerate(mydict): print(index) print(name)

打印结果: 字符串: 0 H 1 e 2 l 3 l 4 o 列表: 0 one 1 two 2 three 3 four 元组: 0 one 1 two 2 three 3 four 集合: 0 two 1 three 2 four 3 one

可以看到,字符串,列表,元组都是顺序的,而集合不是。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3