2016-08-13 4 views
-1

私はPythonを学んでいます。インデックス変数を常に作成することなく、繰り返し可能なオブジェクトをループすることができます。インデックスのないPythonループ

しかし、私はインデックス変数を作成しているので、並列オブジェクトからの呼び出しで参照できるようにしています。 2つのリスト、またはリストと辞書を比較しているときのように。

要求されたよう:いくつかの例

`s= "GAGCCTACTAACGGGAT"# the strings we are evaluating 
t= "CATCGTAATGACGGCCT" 

c = 0# c = position of interest within the strings 
m = 0 # m = number of mutations found so far. 

for i in s: # cycling through all nucleotides listed in s 
if(i == t[c]): #compare s[c] to t[c] 
    c +=1 # if equal, increase position counter 
else: 
    c+=1 # if not equal, increase both position and     
    m+=1  #mutation counters.` 

def allPossibleSubStr(s): #takes a dict of strings, finds the shortest, and produces a list of all possible substrings, thus a list of possible common substrings to all elements of the original dict 
ks = s.keys() 
c=0 #counter 
j=0 # ks place holder for shortest string 
subSTR = [] 

for i in ks: #finds the shortest entry in stringDict 
    if(s[i] < s[ks[(c+1)%len(s)]]): 
     j=c 
    c +=1 

c=s[ks[j]] #c is now a string, the shortest... 
j=ks[j] # j is now a key string, the shortest... 
n = (len(c)*(len(c)+1))/2 # number of subsets of c 

#producing a list of possible substrings 
for i in range(len(c)): 
    for k in range(len(c)-i): 
     subSTR.append(c[i:i+k+1]) 
     #print("i =" +str(i)+ " and k=" + str(k)) 
#is there a list function with eleminates duplicate entries. 
subSTR=list(set(subSTR))# a set does not have any duplicate entires 
subSTR.sort(key=len) # sorts substring from shortest to longest string 
subSTR.reverse() 

return subSTR 

はこれを回避する方法はありますか?

+1

ケアを、あなたが何を意味するかの例を与えることを? –

+2

インデックスの使用方法の例を示してください。ユースケースによっては、他の方法があります。例えば。同時に2つのリストが必要な場合は、 'zip()'を使うことができます。 – poke

+0

私は、私の複数のPythonプロジェクトで1000個以上のループを素早く見てきました。そして、10個以下のインデックスを使用しました( 'enumerate')。だから、おそらくあなたはあなたの意図を表現するためのより良い方法を見落としているでしょう。 – spectras

答えて

2

for i, item in enumerate(myList): 
    foo = parallelList[i] 

またはzipを列挙する:

for i, item in enumerate(list1): 
    if item == list2[i]: 
     ... 

あなたはまだ必要はありません。 2つのリストを解凍してタプルのリストを反復することができるので、明示的なインデックスです。

for item1, item2 in zip(list1, list2): 
    if item1 == item2: 

彼らは順不同であるため、あなたはおそらく、ソート後にキーを圧縮したいが、あなたは、2枚のdictsと同じことを行うことができます

for key1, key2 in zip(sorted(dict1), sorted(dict2)): 
2

使用すると、あなたは、このようなコードを書くようですね... ...

for item, foo in zip(myList, parallelList): 
    ... 
+1

これはインデックスの回避にはあまり役立ちません。 – poke

+1

(ジップの例を追加) –

+0

これで遊ぶ必要があります。私はこれらのコマンドを見たことがありません.zipと列挙。 – Carl

関連する問題