【问题标题】:python loops without index没有索引的python循环
【发布时间】: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)。所以,是的,很可能你忽略了一些更好的方式来表达你的意图。

标签: python loops indexing


【解决方案1】:

听起来你写的代码是这样的:

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

您仍然不需要显式索引,因为您可以压缩两个列表并遍历元组列表。

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

你可以用两个字典做同样的事情,虽然因为它们是无序的,你可能想在排序后压缩它们的键:

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

【讨论】:

    【解决方案2】:

    使用枚举...

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

    或压缩...

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

    【讨论】:

    • 但这并不能真正帮助避免索引。
    • (添加了一个 zip 示例)
    • 我必须玩这些。我之前没见过这些命令.zip 和枚举。
    猜你喜欢
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多