I am trying to iterate through columns in a data file, to perform my task and then save the output to a file. I have almost 200 columns and unfortunately so far I can only get the required output by changing the column index manually (where ###). I have managed to get the index numbers that I want to use from my row names into a list (called x). I've been playing around with this but I am stuck as to how to make it iterate through these indices in the correct places. Below is what I have so far:
我试图遍历数据文件中的列,执行我的任务,然后将输出保存到文件。我有近200列,不幸的是到目前为止,我只能通过手动更改列索引来获得所需的输出(其中###)。我设法将我想要使用的索引号从我的行名称中获取到一个列表中(称为x)。我一直在玩这个但是我很困惑如何让它在正确的地方迭代这些索引。以下是我到目前为止:
with open('matrix.txt', 'r') as file:
motif = file.readline().split()
x = [i for i, j in enumerate(motif)]
print x ### list of indices I want to use
for column in (raw.strip().split() for raw in file):
chr = column[0].split("_")
coordinates = "\t".join(chr)
name = motif[1] ### using column index
print name
for value in column[1]: ### using column index
if value == "1":
print coordinates
out = open("%s.bed" %name, "a")
out.write(str(coordinates)+"\n")
elif value == "0":
pass
When I return x I get:
当我返回x时,我得到:
x = [0, 1, 2, 3, 4,...]
x = [0,1,2,3,4,...]
Using motif[x[1]] returns the correct names and columns, however this is the same as me putting the index in manually. Any help is appreciated!
使用motif [x [1]]返回正确的名称和列,但这与我手动输入索引相同。任何帮助表示赞赏!
1 个解决方案
#1
1
Instead of:
代替:
name = motif[1] ### using column index
print name
for value in column[1]: ### using column index
if value == "1":
print coordinates
out = open("%s.bed" %name, "a")
out.write(str(coordinates)+"\n")
elif value == "0":
pass
you can iterate through x
since x
is a list of the column indices:
你可以迭代x,因为x是列索引的列表:
for index in x:
name = motif[index]
print name
for value in column[index]:
if value == "1":
print coordinates
out = open("%s.bed" %name, "a")
out.write(str(coordinates)+"\n")
elif value == "0":
pass
You can read more about for
loops here.
您可以在此处阅读有关for循环的更多信息
#1
1
Instead of:
代替:
name = motif[1] ### using column index
print name
for value in column[1]: ### using column index
if value == "1":
print coordinates
out = open("%s.bed" %name, "a")
out.write(str(coordinates)+"\n")
elif value == "0":
pass
you can iterate through x
since x
is a list of the column indices:
你可以迭代x,因为x是列索引的列表:
for index in x:
name = motif[index]
print name
for value in column[index]:
if value == "1":
print coordinates
out = open("%s.bed" %name, "a")
out.write(str(coordinates)+"\n")
elif value == "0":
pass
You can read more about for
loops here.
您可以在此处阅读有关for循环的更多信息