2016-09-01 3 views
1

n 개의 DNA 서열이있는 파일이 있다고 가정 해보십시오. 목록으로 변환 한 다음 각 시퀀스의 길이를 계산 한 다음 전체 길이를 합산하여 계산해야합니다. 목록에 들어가기 전에 어떻게해야할지 모르겠습니다.파이썬으로 문자열 목록에 속한 각 문자열 길이를 계산하는 방법은 무엇입니까?

# open file and writing each sequences' length 
f= open('seq.txt' , 'r') 
for line in f: 
    line= line.strip() 
    print (line) 
    print ('this is the length of the given sequence', len(line)) 

# turning into a list: 
lines = [line.strip() for line in open('seq.txt')] 
print (lines) 

목록에서 어떻게 산술 계산을 할 수 있습니까? 전의. 모든 시퀀스의 총 길이는 함께 나타 납니까? 다른 길이의 표준 편차 등

+0

저는 전체 시퀀스로서 개별 시퀀스의 길이 목록을 작성하는 방법을 보여주는 대답을했습니다. 일단 길이 목록이 있으면 그것에 관한 통계를 할 수 있습니다. – sabbahillel

답변

1

statistics 모듈을 살펴보십시오. 모든 종류의 평균 및 스프레드를 찾을 수 있습니다.

len을 사용하여 모든 시퀀스의 길이를 가져옵니다. 귀하의 경우에는

, 당신은 그들의 길이에 시퀀스를 매핑 할 수 있습니다 :

from statistics import stdev 

with open("seq.txt") as f: 
    lengths = [len(line.strip()) for line in f] 

print("Number of sequences:", len(lengths)) 
print("Standard deviation:", stdev(lengths)) 

편집 : 그것은 코멘트에 질문을 받았다 때문에 : 여기에 따라 다른 파일에 인스턴스를 클러스터하는 방법 자신의 길이 :

from statistics import stdev, mean 
with open("seq.txt") as f: 
    sequences = [line.strip() for line in f] 
lengths = [len(sequence) for sequence in sequences] 

mean_ = mean(lengths) 
stdev_ = stdev(lengths) 

with open("below.txt", "w") as below, open("above.txt", "w") as above, open("normal.txt", "w") as normal: 
    for sequence in sequences: 
     if len(sequence) > mean+stdev_: 
      above.write(sequence + "\n") 
     elif mean+stdev_ > len(sequence > mean-stdev_: #inbetween 
      normal.write(sequence + "\n") 
     else: 
      below.write(sequence + "\n") 
+0

내 파일에 수치 데이터가 없습니다. 오직 DNA 문자열. len (줄)을 할 때, 그것은 내가 가지고있는 문자열의 개수를 제공하지만 모든 문자열의 전체 길이를 함께 제공하지는 않습니다. –

+0

길이가 작동하는지 알아보기 위해 float 또는 int를 사용하려고했으나하지 않았습니다. –

+0

모든 시퀀스의 전체 길이를 원하면'sum (lengths)'를 사용하십시오. – L3viathan

0

몇 가지 비고. with을 사용하여 파일을 처리하십시오. \ 쓰기, 플러싱 등을 읽은 후에 닫는 것에 대해 걱정하지 않아도됩니다. 또한 파일을 한 번 반복하므로 왜 목록을 만들지 않습니까? 당신은 그것을 다시 통과 할 필요가 없습니다.

# open file and writing each sequences' length 
with open('seq.txt', 'r') as f: 
    sequences = [] 
    total_len = 0 
    for line in f: 
     new_seq = line.strip() 
     sequences.append(new_seq) 
     new_seq_len = len(new_seq) 
     total_len += new_seq_len 

print('number of sequences: {}'.format(len(sequences))) 
print('total lenght: {}'.format(total_len)) 
print('biggest sequence: {}'.format(max(sequences, key=lambda x: len(x)))) 
print('\t with length {}'.format(len(sorted(sequences, key=lambda x: len(x))[-1]))) 
print('smallest sequence: {}'.format(min(sequences, key=lambda x: len(x)))) 
print('\t with length {}'.format(len(sorted(sequences, key=lambda x: len(x))[0]))) 

나는 그것에 대해 어떻게 생각하는지 알려주는 몇 가지 사후 처리 정보가 포함되어 있습니다. 궁금한 점이 있으면 문의하십시오.

+0

감사합니다! 그래서, 예 : lines = [line.strip() in open ('seq.txt')] 라인을 사용하여 목록을 만들었습니다. 그럼 내 목록은 [ 'AGATAAGATAGTAGAT', 'GTAAGTGATGATAGTAGTA'등]입니다. 그러나 일단 길이 len (선)을하려고하면 모든 문자열의 전체 길이가 아니라 전체 문자열 수만 제공합니다. –

+0

나는 또한 len (lines [0 :])을 시도했다. 작동하지 않습니다. –

+0

@MarinaMitieMonobe 여기가 발생합니다. 'total_len + = new_seq_len' –

2

출력에 각각의 길이를이 시도하고 총 길이 계산 :

,321을 0
0

append를 사용하여 시퀀스 목록과 길이 목록을 얻는 방법을 이미 보았습니다. 당신은 또한 각 라인을 읽고 추가 두리스트보다는리스트를 통해 모든 목록에 선 다음 루프를 읽을 루프를 사용할 수 있습니다

lines = [line.strip() for line in open('seq.txt')] 
    total = 0 
    sizes = [] 
    for line in lines: 
     mysize = len(line) 
     total += mysize 
     sizes.append(mysize) 

참고. 그것은 당신이 선호하는 문제입니다.

통계 라이브러리 (Python 3.4)를 사용하여 길이 목록 통계를 볼 수 있습니다.

statistics — Mathematical statistics functions

mean() Arithmetic mean (“average”) of data. median() Median (middle value) of data. median_low() Low median of data.
median_high() High median of data. median_grouped() Median, or 50th percentile, of grouped data. mode() Mode (most common value) of discrete data. pstdev() Population standard deviation of data.
pvariance() Population variance of data. stdev() Sample standard deviation of data. variance() Sample variance of data.

는 또한 실제로 통계 모듈에 대한 파이썬 3.4에 추가 된 코드를 보여줍니다 답이 있음을 Standard deviation of a list

주에 답변을 사용할 수 있습니다. 이전 버전을 사용하는 경우 해당 코드를 사용하거나 자신의 시스템에 대한 통계 모듈 코드를 얻을 수 있습니다.

1

지도 및 축소 기능은 컬렉션 작업에 유용 할 수 있습니다.

import operator 

f= open('seq.txt' , 'r') 
for line in f: 
    line= line.strip() 
    print (line) 
    print ('this is the length of the given sequence', len(line)) 

# turning into a list: 
lines = [line.strip() for line in open('seq.txt')] 
print (lines) 

print('The total length is 'reduce(operator.add,map(len,lines))) 
0

이렇게하면 필요한 작업을 수행 할 수 있습니다. 추가 계산을 수행하려면 텍스트 파일의 결과를 목록이나 세트로 저장하여 파일에서 다시 읽을 필요가 없도록 할 수 있습니다.

total_length = 0 # Create a variable that will save our total length of lines read 

with open('filename.txt', 'r') as f: 
    for line in f: 
     line = line.strip() 
     total_length += len(line) # Add the length to our total 
     print("Line Length: {}".format(len(line))) 

print("Total Length: {}".format(total_length)) 
관련 문제