![](/img/trans.png)
[英]Use levenshtein distance for keys in defaultdict in python
[英]Python - grouping defaultdict values by hamming distance in keys
我有一個約700個密鑰的默認字典。 密鑰的格式為A_B_STRING。 我需要做的是將鍵分成'_',並比較每個鍵的'STRING'之間的距離,如果A和B相同的話。 如果距離<= 2,我想將這些鍵的列表分組到一個defaultdict鍵:值組中。 將有多個密鑰應匹配並進行分組。 我還想保留新的組合defaultdict,所有關鍵:沒有進入組的值對。
輸入文件是FASTA格式,其中標題是鍵,值是序列(因為多個序列具有基於原始fasta文件的blast報告的相同標題,所以使用defaultdict)。
這是我到目前為止:
!/usr/bin/env python
import sys
from collections import defaultdict
import itertools
inp = sys.argv[1] # input fasta file; format '>header'\n'sequence'
with open(inp, 'r') as f:
h = []
s = []
for line in f:
if line.startswith(">"):
h.append(line.strip().split('>')[1]) # append headers to list
else:
s.append(line.strip()) # append sequences to list
seqs = dict(zip(h,s)) # create dictionary of headers:sequence
print 'Total Sequences: ' + str(len(seqs)) # Numb. total sequences in input file
groups = defaultdict(list)
for i in seqs:
groups['_'.join(i.split('_')[1:])].append(seqs[i]) # Create defaultdict with sequences in lists with identical headers
def hamming(str1, str2):
""" Simple hamming distance calculator """
if len(str1) == len(str2):
diffs = 0
for ch1, ch2 in zip(str1,str2):
if ch1 != ch2:
diffs += 1
return diff
keys = [x for x in groups]
combos = list(itertools.combinations(keys,2)) # Create tupled list with all comparison combinations
combined = defaultdict(list) # Defaultdict in which to place groups
for i in combos: # Combo = (A1_B1_STRING2, A2_B2_STRING2)
a1 = i[0].split('_')[0]
a2 = i[1].split('_')[0]
b1 = i[0].split('_')[1] # Get A's, B's, C's
b2 = i[1].split('_')[1]
c1 = i[0].split('_')[2]
c2 = i[1].split('_')[2]
if a1 == a2 and b1 == b2: # If A1 is equal to A2 and B1 is equal to B2
d = hamming(c1, c2) # Get distance of STRING1 vs STRING2
if d <= 2: # If distance is less than or equal to 2
combined[i[0]].append(groups[i[0]] + groups[i[1]]) # Add to defaultdict by combo 1 key
print len(combined)
for c in sorted(combined):
print c, '\t', len(combined[c])
問題是此代碼無法按預期工作。 在組合的defaultdict中打印鍵時; 我清楚地看到有許多可以結合起來。 但是,組合defaultdict的長度大約是原始大小的一半。
編輯
替代方案沒有itertools.combinations:
for a in keys:
tocombine = []
tocombine.append(a)
tocheck = [x for x in keys if x != a]
for b in tocheck:
i = (a,b) # Combo = (A1_B1_STRING2, A2_B2_STRING2)
a1 = i[0].split('_')[0]
a2 = i[1].split('_')[0]
b1 = i[0].split('_')[1] # Get A's, B's, C's
b2 = i[1].split('_')[1]
c1 = i[0].split('_')[2]
c2 = i[1].split('_')[2]
if a1 == a2 and b1 == b2: # If A1 is equal to A2 and B1 is equal to B2
if len(c1) == len(c2): # If length of STRING1 is equal to STRING2
d = hamming(c1, c2) # Get distance of STRING1 vs STRING2
if d <= 2:
tocombine.append(b)
for n in range(len(tocombine[1:])):
keys.remove(tocombine[n])
combined[tocombine[0]].append(groups[tocombine[n]])
final = defaultdict(list)
for i in combined:
final[i] = list(itertools.chain.from_iterable(combined[i]))
但是,通過這些方法,我仍然缺少一些與其他方法不匹配的方法。
我想我看到你的代碼有一個問題考慮這個場景:
0: A_B_DATA1
1: A_B_DATA2
2: A_B_DATA3
All the valid comparisons are:
0 -> 1 * Combines under key 'A_B_DATA1'
0 -> 2 * Combines under key 'A_B_DATA1'
1 -> 2 * Combines under key 'A_B_DATA2' **opps
我想你會想要所有這三個在1鍵下合並。 但請考慮以下情況:
0: A_B_DATA111
1: A_B_DATA122
2: A_B_DATA223
All the valid comparisons are:
0 -> 1 * Combines under key 'A_B_DATA111'
0 -> 2 * Combines under key 'A_B_DATA111'
1 -> 2 * Combines under key 'A_B_DATA122'
現在它有點棘手,因為第0行是第1行的距離2,第1行是第2行的距離2,但是你可能不希望它們全部在一起,因為第0行距離第2行的距離為3!
下面是一個工作解決方案的示例,假設您希望輸出看起來像這樣:
def unpack_key(key):
data = key.split('_')
return '_'.join(data[:2]), '_'.join(data[2:])
combined = defaultdict(list)
for key1 in groups:
combined[key1] = []
key1_ab, key1_string = unpack_key(key1)
for key2 in groups:
if key1 != key2:
key2_ab, key2_string = unpack_key(key2)
if key1_ab == key2_ab and len(key1_string) == len(key2_string):
if hamming(key1_string, key2_string) <= 2:
combined[key1].append(key2)
在我們的第二個例子中,這將導致以下字典,如果這不是您正在尋找的答案,您是否可以輸入該示例的最終字典應該是什么?
A_B_DATA111: ['A_B_DATA122']
A_B_DATA122: ['A_B_DATA111', 'A_B_DATA223']
A_B_DATA223: ['A_B_DATA122']
請記住,這是一個O(n ^ 2)算法,這意味着當您的密鑰集變大時,它不可擴展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.