python一个数组中有重复值时的Index函数返回值以及引出的其他问题

问题引出:

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]
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值