如何在Python中获取列表中特定值的范围?
例如,我有一个列表如何在Python中获取列表中特定值的范围?,python,Python,例如,我有一个列表 my_list=[['E', '101_CHEK1'], ['E', '101_CHEK1'], ['E', '101_CHEK1'], ['B', '101_CHEK1'], ['B', '101_CHEK1'], ['E', '101_CHEK1'], ['E', '101_CHEK1'], ['E', '101_CHEK1'], ['B', '101_CHEK1'], ['E', '101_CHEK1']] 如何获取列表中第一个元素的范围,即:[0-2], B:[3-
my_list=[['E', '101_CHEK1'],
['E', '101_CHEK1'],
['E', '101_CHEK1'],
['B', '101_CHEK1'],
['B', '101_CHEK1'],
['E', '101_CHEK1'],
['E', '101_CHEK1'],
['E', '101_CHEK1'],
['B', '101_CHEK1'],
['E', '101_CHEK1']]
如何获取列表中第一个元素的范围,即:[0-2],
B:[3-4],E:[5-7]。。。。到目前为止,我得出的结论如下:
d={}
a=0
for j,i in enumerate(my_list):
a+=1
if i[0] not in d:
d[i[0]]=[j]
else:
d[i[0]].append(j)
{'B':[3,4,8],'E':[0,1,2,5,6,7,9]}
有什么特别的方法我应该遵循吗?最终O/P应为
E:[0-2],B:[3-4],E:[5-7]
注释中的解释
my_list=[['E', '101_CHEMBL1236539_CHEK1'],['E', '101_CHEMBL1236539_CHEK1'],['E', '101_CHEMBL1236539_CHEK1'],['B', '101_CHEMBL1236539_CHEK1'],['B', '101_CHEMBL1236539_CHEK1'],['E', '101_CHEMBL1236539_CHEK1'],['E', '101_CHEMBL1236539_CHEK1'],['E', '101_CHEMBL1236539_CHEK1'],['B', '101_CHEMBL1236539_CHEK1'],['E', '101_CHEMBL1236539_CHEK1']]
from collections import defaultdict
dic = defaultdict(list)
# create a simple dictionary with element position for each elemets
for i,ele in enumerate(my_list):
dic[ele[0]] = dic[ele[0]]+[i]
# next problem: get consecutive groups [1,2,4,5,6] ==> (1,2),(4,6)
# You can also use more_iterrools.consecutive_groups here.
# Implementation taken from https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/more.html#consecutive_groups
from itertools import groupby
from operator import itemgetter
def get_consecutive_groups(iterables):
groups = []
for k, g in groupby(enumerate(iterables), key=lambda x: x[0] - x[1]):
g = list(map(itemgetter(1), g))
groups.append((g[0],g[-1]))
return (groups)
#create a new dictionary where we have the groupings stored
new_dic = {}
for key in dic.keys():
new_dic[key] = get_consecutive_groups(dic[key])
print(new_dic)
输出:
{'E': [(0, 2), (5, 7), (9, 9)], 'B': [(3, 4), (8, 8)]}
{'B': [3, 4, 8], 'E': [0, 1, 2, 5, 6, 7, 9]}
嗯,你可以把它缩短:
dict_example = {'B': [x for x in range(len(my_list)) if my_list[x][0] == 'B'], 'E': [x for x in range(len(my_list)) if my_list[x][0] == 'E']}
print(dict_example)
输出:
{'E': [(0, 2), (5, 7), (9, 9)], 'B': [(3, 4), (8, 8)]}
{'B': [3, 4, 8], 'E': [0, 1, 2, 5, 6, 7, 9]}
作为字典,您将无法获得预期的结果,因为您有重复键。是否有其他输出或类型?这很好。只是一个问题,我在运行代码时遇到如下错误:
namererror:name'itemgetter'未定义