码迷,mamicode.com
首页 > 其他好文 > 详细

取出列表相应值的位置(表处理)

时间:2016-07-06 18:44:01      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:列表

#需求

在一个列表中,取出相应值的位置


方法1:

#脚本示例

[root@localhost opt]# cat list.py 
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
name=[‘!‘,‘#‘,‘*‘,‘Eric‘,‘wsyht‘,‘jack‘,‘jack‘,‘a‘,‘b‘,‘c‘,‘d‘,1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,2332,4,2,6,2]
first_pos = 0
for i in range(name.count(2)):  #5个2
        new_list = name[first_pos:]
        next_pos = new_list.index(2) + 1   #第一个元素位置在12 , 再+1,下个一位置开始寻找下一个元素位置
        print ‘Find postion:‘, first_pos + new_list.index(2),‘Next:‘, next_pos  #12, 13
        first_pos += next_pos  #0+13


#执行脚本

[root@localhost opt]# python list.py 
Find postion: 12 Next: 13
Find postion: 18 Next: 6
Find postion: 24 Next: 6
Find postion: 31 Next: 7
Find postion: 33 Next: 2


方法2:

#脚本示例

#!/usr/bin/env python
#conding:utf-8
a = [1,0,2,3,4,5,6,7,8,1,2,3,4,5,6,1,2,3,4,5]
pos = 0
for i in range(a.count(2)):  #统计出现2的次数
if pos == 0:
pos = a.index(2)         #查找第一个值出现的位置,赋值为pos
else:
pos = a.index(2,pos+1)   #2为查找的数,从pos+1的位置开始找
print pos


#执行脚本

[root@localhost opt]# python list_count.py 
12
18
24
31
33



本文出自 “wsyht的博客” 博客,请务必保留此出处http://wsyht2015.blog.51cto.com/9014030/1797556

取出列表相应值的位置(表处理)

标签:列表

原文地址:http://wsyht2015.blog.51cto.com/9014030/1797556

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!