我正在使用python2.7。我有一个包含染色体位置和实验ID的文件。我目前已将这些信息存储在两个列表中:
unique_locations - containing a single value for each location
location_exp - containing lists of [location, experiment]
我没有使用字典的原因是在多个实验中找到了多个位置 - 即这是一个很多很多的关系。
我想了解每个位置的实验数量。我得到一个如下列表:
[
[location1, [experiment1, experiment2, experiment3]],
[location2, [experiment2, experiment3, experiment4]]
]
等
由于列表的长度不同,我在两个列表中使用枚举(列表)循环都失败了。我试过了:
location_experiment_sorted = []
for i, item in enumerate(unique_experiment):
location = item[0]
exp = item[1]
if location not in location_experiment_sorted:
location_experiment_sorted.append([location, exp])
else:
location_experiment_sorted[i].append(exp)
除此之外。我也尝试使用与多个实验列表相关的字典。有人能指出我正确的方向吗?
答案 0 :(得分:2)
如果我理解你的话 (如果位置可以用作dict键)
你可以这样做:location_experiments={}
for location, experiment in location_exp:
location_experiments.setdefault(location,[]).append(experiment)
答案 1 :(得分:2)
尝试defaultdict,即:
$("#dataset\\.recordids\\.Products option")
将打印出来:
from collections import defaultdict
unique_locations = ["location1", "location2"]
location_exp = [
("location1", "experiment1"),
("location1", "experiment2"),
("location1", "experiment3"),
("location2", "experiment2"),
("location2", "experiment3"),
("location2", "experiment4")
]
location_experiment_dict = defaultdict(list)
for location, exp in location_exp:
location_experiment_dict[location].append(exp)
print(location_experiment_dict)
答案 2 :(得分:1)
我还没有这样做,如果失败就道歉。 如果你说它是[[位置,实验],[位置,实验]]等列表,那么:
locationList = {}
for item in unique_experiment:
location = item[0]
exp = item[1]
if location not in locationList:
locationList[location] = []
locationList[location].append(exp)
else:
locationList[location].append(exp)
答案 3 :(得分:1)
以下是另一个工作示例,使用来自dict
的内置groupby
和itertools
:
>>> from itertools import groupby
>>> d = {}
>>> location_exp = [
("location1", "experiment1"),
("location1", "experiment2"),
("location1", "experiment3"),
("location2", "experiment2"),
("location2", "experiment3"),
("location2", "experiment4")
]
>>> for k,v in groupby(location_exp, itemgetter(0)):
d.setdefault(k,[])
d[k].extend([loc for _, loc in v])
[]
[]
>>> d
{'location2': ['experiment2', 'experiment3', 'experiment4'], 'location1': ['experiment1', 'experiment2', 'experiment3']}
>>>
>>> d2 = {}
>>> location_exp2 = [
("location1", "experiment1"),
("location2", "experiment2"),
("location3", "experiment3"),
("location1", "experiment2"),
("location2", "experiment3"),
("location3", "experiment4")
]
>>> for k,v in groupby(location_exp2, itemgetter(0)):
d2.setdefault(k,[])
d2[k].extend([loc for _, loc in v])
[]
[]
[]
['experiment1']
['experiment2']
['experiment3']
>>> d2
{'location2': ['experiment2', 'experiment3'], 'location1': ['experiment1', 'experiment2'], 'location3': ['experiment3', 'experiment4']}