Lists in Python - AttributeError: 'str' object does not have 'coeffs' attribute

I have a list problem in python.

here are simple codes:

x = [scipy.poly1d([ 1.,  0.,  0.]),2,3,4,5,'foward']
for i in range (len(x)) :
    if x [i] == 'foward':
        print 'check!'

when it starts, it will say:

return NX.alltrue (self.coeffs == other.coeffs) AttributeError: object 'str' does not have attribute 'coeffs'

but when i change x to:

  x = [1,2,3,4,5,'foward']

the program will not work.

can someone explain to me why? What should I do? in fact, I have a list of data fixes (x) that return an attribute error, as mentioned above, and I don’t want to change its format and what it contains.

+3
source share
3 answers
if isinstance(x[i], basestring) and x[i] == 'forward'

or fast and dirty:

if str(x[i]) == 'forward'

You should also use a loop for .. into iterate over the list:

for elem in x:
    if isinstance(elem, basestring) and elem == 'forward':
        print 'Check'

If you need itoo:

for i, elem in enumerate(x):
+5

, , , scipy.poly1d. , , "" . "forward" coeff, .

if try/except:

try:
   if x[i] == 'forward':
      print 'check'
except AttributeError:
   pass

- :

for i in range(len(obj)): 
    x=obj[i]
    ...

- . :

for i,x in enumerate(obj):
    ...
+1

If you just want to check if there is a "foward" in the list, you can also use

if 'foward' in [i for i in x if isinstance(i, basestring)]:
    print 'check'
0
source

All Articles