我使用的是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]]
]
等等
由于列表的长度不同,我在任一列表上使用 enumerate(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)
除其他事项外。我也尝试过使用与多个实验列表相关的字典。谁能指出我正确的方向?
最佳答案
如果我理解正确的话 (如果位置可以用作字典键)
你可以这样做:
location_experiments={}
for location, experiment in location_exp:
location_experiments.setdefault(location,[]).append(experiment)
关于python - 创建一个与列表关联的字典并通过循环更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38587083/