有幾種方法,你可以生成表,用頭。你可以例如用一個額外的行和一個額外的列創建表(您稱爲plot
,我已在下面的代碼中重命名爲table
),然後用核酸序列中的字母填充額外的行和列。這是如下所示:
def dotplot(seqx,seqy):
table = [[" "*3 for x in range(len(seqx) + 1)] for y in range(len(seqy) + 1)] # increased the size of an element in the table (3 spaces)
# fill the column headers
table[0][1:] = [" %c " % (char,) for char in seqx]
# fill the row headers:
for row, char in zip(table[1:], seqy):
row[0] = " %c " % (char,)
# fill the content-part of the table
for yindex, yvalue in enumerate(seqy):
for xindex, xvalue in enumerate(seqx):
if xvalue == yvalue: # your decision logic: when to add a star
table[yindex + 1][xindex + 1] = " * " # Also added some spaces here
return table
for row in table:
print(''.join(row)) # chain together the elements in each `row` list
注意,我已經改變很少你的大部分功能dotplot
的。只有遍歷表的順序(第一行,然後是行內的列)已被更改,並且已添加一個偏移量(例如,yindex + 1
)以說明添加的行和列標題。
另一種方法是交織打印表格,打印行和列標題。在下面的代碼中,我已經導入了print-function,它增加了Python3的功能,使得Python2.7中的這個功能變得更加簡單。
from __future__ import print_function
def dotplot(seqx,seqy):
table = [[" "*3 for x in seqx] for y in seqy] # increased the size of an element in the table (3 spaces)
# print the column headers:
print(' '*3 + ''.join(" %c " % (char,) for char in seqx)) # adds leading whitespace (for the row headers) and the characters from `seqx` with extra whitespace
# print the table
for yindex, yvalue in enumerate(seqy):
for xindex, xvalue in enumerate(seqx):
if xindex == 0: # first column -> add the row headers
print(' %c ' % (yvalue,), end='')
if xvalue == yvalue: # your decision logic: when to add a star
table[yindex][xindex] = " * " # Also added some spaces here
print(''.join(table[yindex]))
return table
這兩種方法都將打印此表的表:
a c t g c t g
a *
g * *
g * *
g * *
a *
t * *
我沒有改變的邏輯代碼中的指定時添加的明星。在邏輯只檢查覈鹼基之間是否相等的時刻(if xvalue == yvalue:
),這就是爲什麼每次有匹配時你都會看到星星。我的猜測是這不是你想要的,所以你應該重新考慮這種情況下的邏輯。但是,您的問題涉及添加列標題和行標題,我希望這些標題可以讓您繼續。
此外,如果您正在使用核酸序列進行大量工作,則應考慮查看BioPython。
看來你正在試圖創建一個帶有星號的ASCII藝術表格,表示兩個序列元素之間的等價關係。你怎麼想這個頭?在表格前打印一行文字?如果是這樣,請在第一個'for'循環之前使用另一個'print'語句。如果沒有,請通過添加所需結果的示例(例如帶有標題的ASCII藝術表格)來澄清您的問題。 –
我已經更新了我所需的輸出。我想我將不得不在第一個for循環之前插入另一個print語句,但我仍然很困惑。 – Ana