python一个数组中有重复值时的Index函数返回值以及引出的其他问题
问题引出:python中list.index()可以返回获得一个数据的索引值,但是有两个相同的值,只会返回第一个数据的索引>>> s = [11, 22, 33, 44, 22, 11]>>> s.index(11)0>>> s.index(22)1>>> from collections import defa...
·
问题引出:
python中list.index()可以返回获得一个数据的索引值,但是有两个相同的值,只会返回第一个数据的索引
>>> s = [11, 22, 33, 44, 22, 11]
>>> s.index(11)
0
>>> s.index(22)
1
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for index,val in enumerate(s):
... d[val].append(index)
...
>>> d
defaultdict(<class 'list'>, {11: [0, 5], 22: [1, 4], 33: [2], 44: [3]})
>>> d[11]
[0, 5] #即11的索引为0和5
>>>
突然发现这些知识点也不熟:
1> enumerate()函数:
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中或使用list将其转化为元组数组
>>> directions = ['east','west','north','south']
>>> list(enumerate(directions))
[(0, 'east'), (1, 'west'), (2, 'north'), (3, 'south')]
>>> list(enumerate(directions,start=1)) #可以指定开始的坐标
[(1, 'east'), (2, 'west'), (3, 'north'), (4, 'south')]
>>> for i,j in enumerate(directions):
... print(i,j)
...
0 east
1 west
2 north
3 south
2> 使用collections.defaultdict()构造列表字典:
一般的字典变量要是访问呢不存在的 key 时会引发‘KeyError’异常,使用collections类中的defaultdict()方法来为字典提供默认值。
使用list作第一个参数,可以很容易将键-值对序列转换为列表字典
from collections import defaultdict
s = [11, 22, 33, 44, 22, 11]
d = defaultdict(list) #将键值对序列转换为列表字典 要是集合字典此处参数为set
for k, v in enumerate(s): #k为数据下标,v为数据
d[v].append(k)
print(d)
运行结果为列表字典:
defaultdict(<class 'list'>, {11: [0, 5], 22: [1, 4], 33: [2], 44: [3]})
3> 字典的items()函数
字典的items() 函数以列表返回可遍历的(键, 值) 元组数组
即将字典转化为元组列表 ,可以使用for循环对其进行操作
在python2中d.items()是一个list类型
在python3中d.items()是一个dict_items类型
>>> s = [11, 22, 33, 44, 22, 11]
>>> d={11: [0, 5], 22: [1, 4], 33: [2], 44: [3]}
>>> type(d.items())
<class 'dict_items'>
>>> type(d)
<class 'dict'>
>>> d.items()
dict_items([(11, [0, 5]), (22, [1, 4]), (33, [2]), (44, [3])])
>>> sorted(d.items()) #经sorted返回列表形式
[(11, [0, 5]), (22, [1, 4]), (33, [2]), (44, [3])]
>>> for key,value in d.items():
... print(key,value)
...
11 [0, 5]
22 [1, 4]
33 [2]
44 [3]
更多推荐

所有评论(0)