Home > Net >  How to deal with iteracy python
How to deal with iteracy python

Time:01-15

I'm writing this function:

def PCP(seq, feature):
  l=[]
  mean= st.mean(list(feature.values()))
  std= np.std(list(feature.values()))
  for elem in range(len(seq)):
    for s in elem:
      if s==feature.keys[s]:
         l.append((feature.values[s]-mean)/std)
      else:
         l.append(0)
      return l

Where seq is a list of string with sequences, and feature is a dict with aminoacids as keys and certain values as values. I want the function to get throught evry aa in a string in the list (seq) and take the values that corresponds in the dict and make calculation.

Still getting errors about iteracy...could anybody help me??

CodePudding user response:

'range' returns a list of numbers.

therefore 'elem' is a number.

therefore it is not iterable.

do you mean 'for elem in seq' ?

CodePudding user response:

Here's a modified version of your code that should work:

def PCP(seq, feature):
  l = []
  mean = st.mean(list(feature.values()))
  std = np.std(list(feature.values()))
  for elem in seq:
      for aa in elem:
          if aa in feature:
              l.append((feature[aa]-mean)/std)
          else:
              l.append(0)
  return l

The main changes I made were:

  • Instead of using "range(len(seq))" to iterate through the list of sequences, I used "seq" directly. This way, "elem" will be the actual string in the list, instead of the index of the string.
  • Inside the nested loop, I used "aa" as the variable to iterate through the characters in the string.
  • When checking if the current character is "in" the feature dictionary, I used the in keyword instead of "keys[s]". This is because "keys()" is a method that returns a list-like object of the dictionary's keys, and you need to use "[]" to access an item in the list. Since "aa" is a string and not an index, you can just check if it's in the dictionary directly.
  • I moved the "return l" statement outside of the nested loop, so that it only happens once after all the calculations are done.

With these changes, the code should work as expected and append the calculated values to the l list for each amino acid in the sequences that has a corresponding value in the feature dictionary.

  • Related