【发布时间】:2016-08-13 22:54:54
【问题描述】:
我正在学习 python,我喜欢你可以循环遍历可迭代对象而无需不断创建索引变量。
但是我发现自己一直在创建索引变量,所以我可以在来自并行对象的调用中引用它们。就像我比较两个列表或一个列表和一个字典时一样。
根据要求:一些例子
`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
有没有办法解决这个问题?
【问题讨论】:
-
想举个例子说明你的意思吗?
-
请举例说明您需要使用索引的内容。根据您的用例,可能还有其他方法。例如。如果你有两个需要同时迭代的列表,你可以使用
zip()。 -
我刚刚快速浏览了我的多个 python 项目中的 1000 多个 for 循环,以及不到 10 个使用索引(
enumerate)。所以,是的,很可能你忽略了一些更好的方式来表达你的意图。