创建一个与列表关联的字典,并通过循环更新它

2024-05-16 23:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是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]]
                                                             ]

等等

由于列表的长度不同,我在任一列表上使用枚举(list)循环都失败了。我确实试过:

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)

除此之外。我也试过使用一本字典,里面有一系列的实验。有人能给我指出正确的方向吗?你知道吗


Tags: 文件in列表for字典locationitemexperiment
3条回答

试试defaultdict,即:

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)

将打印:

defaultdict(<type 'list'>, {
    'location2': ['experiment2', 'experiment3', 'experiment4'],
    'location1': ['experiment1', 'experiment2', 'experiment3']
})

如果我没听错的话 (如果位置可用作dict键)

你可以做:

location_experiments={}
for location, experiment in location_exp:
    location_experiments.setdefault(location,[]).append(experiment)

我没有运行这个,所以如果失败了,我道歉。 如果你说这是一个列表,比如[[位置,实验],[位置,实验]],那么:

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)

相关问题 更多 >