如何用变量连接两个未知大小的依赖输入

2024-10-02 18:16:42 发布

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

这是我的第一个python脚本。我的数据如下:

Position ind1 ind2 ind3 ind4 ind5 ind5 ind7 ind8
 0        C    A     C   A    A    A    A     A
 1        C    A     C   C    C    A    A     A

但它可能在许多列中有所不同,并且有数千行。你知道吗

我的脚本执行我需要的操作,它逐行读取这个文件,并计算每个位置(POS)中个体组合(以下称为population)的A和C的频率。例如,对于总体1(ind1,ind2,ind3,ind4),位置0处的频率;对于总体2(ind5,ind6,ind7,ind8),位置0处的频率,那么对于位置1,2,3。。。。你知道吗

为此,我通过以下代码在脚本中定义列(填充)的组合:

alleles1 = alleles[1:5]
alleles2 = alleles[5:]

但是如果我有9个以上的列和不同的列组合,我需要修改等位基因*和脚本的其余部分。你知道吗

我想让我的程序更具交互性,即用户定义填充的数量并指定哪个列对应于哪个填充。

到目前为止我掌握的代码是:

#ask for the number of populations
try:
    num_pop = int(raw_input("How many populations do you have? > "))
except ValueError:
    print "In is not an integer! \nThe program exits...\n "
#ask for individuals in population
ind_pop = {}
for i in range(num_pop):
    i += 1
    ind_input = str(raw_input("Type column numbers of population %i > " % i))
    ind_pop[i] = re.findall(r'[^,;\s]+', ind_input)

如果我有2个总体,其中第3、5、6列是总体1,第2、5列是总体2。其工作原理如下:

> How many populations do you have? > 2
> Type column numbers of population 1 > 3, 5, 6  
> Type column numbers of population 2 > 2, 4 

输入保存在字典中。你知道吗

{1: ['3', '5', '6'], 2: ['2', '4']}

问题是如何从这个输入开始定义等位基因。 输出应如下所示:

allele1 =  [allele[3], allele[5], allele[6]]
allele2 =  [allele[2], allele[4]]

如果有必要,以下是代码其余部分的主要部分:

with open('test_file.txt') as datafile:
  next(datafile)
  for line in datafile:
    words = line.split() #splits string into the list of words 
    chr_pos = words[0:2] #select column chromosome and position
    alleles = words[2:] # this and next separates alleles for populations

    alleles1 = alleles[0:4]
    alleles2 = alleles[4:8]
    alleles3 = alleles[8:12]
    alleles4 = alleles[12:16]

    counter1=collections.Counter(alleles1)
    counter2=collections.Counter(alleles1)
    counter3=collections.Counter(alleles1)
    counter4=collections.Counter(alleles1)
#### the rest of the code and some filters within the part above were spiked

Tags: ofthe脚本forinputcolumnpopwords
3条回答

首先需要将列号转换为整数

    ind_pop[i] = [int(j) for j in re.findall(r'[^,;\s]+', ind_input)]

(我还要将正则表达式更改为r'\d+'

然后,不要使用alleles1alleles2等,而是使用主列表或字典:

master = {i: [alleles[j] for j in vals] for i, vals in ind_pop.items()}
counters = {i: collections.Counter(al) for i, al in master.items()}

然后您可以访问counters[i]而不是counter1

作为补充说明,您可以通过将ind_pop生成一个列表,使用append而不是保留计数器来简化上面的所有内容

谢谢你的建议。其中一些是有用的。我觉得我需要改变方向。我将继续处理以下列表:

pop_alleles = []
for key in ind_pop.keys():
  pop_alleles.append([alleles[el] for el in ind_pop[key]])

如果这是你想要的结果

allele1 =  [allele[3], allele[5], allele[6]]
allele2 =  [allele[2], allele[4]]

你有这个:

{1: ['3', '5', '6'], 2: ['2', '4']}

从这里开始很简单。你知道吗

for index in population_dict[1]:
    allele1.append(allele[index])
for index in population_dict[2]:
    allele2.append(allele[index])

哦,如果索引是以字符串的形式存储的,因为它们看起来像在上面,那么您需要首先将它们设为int。你可以把上面的内容改成等位基因[int(index)],但最好是在你读的时候把它们改成int。你知道吗

相关问题 更多 >