How is this not a sequence?

I run a list containing a list of numbers as a string, so the list looks like this:

vals = ['0.13', '324', '0.23432']

and try to make a list like this:

best = [x for x in vals > 0.02]

and I get TypeError: iterating over non-sequence.

Isn't a list a sequence that should be the first one you have to iterate through? What is a sequence?

It is difficult to find answers to the basic questions that I find.

Thank.

+3
source share
4 answers

You need to check if each element exceeds 0.02, and not more.

best = [x for x in vals if x > '0.02']

Your original expression is [x for x in vals > '0.02']parsed as [x for x in (vals > '0.02')]. Since it vals > '0.02'is a Boolean value, not a sequence, it is impossible to iterate over it.

EDIT: , '0.02' Joe (). , , , :

best = [x for x in vals if float(x) > 0.02]

x float, , , . - , [x for ...], [float(x) for ...]. .

+8

, vals > 0.02 . , ( vals) . , :

vals = [0.13, 324.0, 0.23432]
best = [x for x in vals if x > 0.02]

NumPy. :

from numpy import *
vals = asarray([0.13, 324.0, 0.23432])
best = vals[vals > 0.02]

, , , .

+4

You are trying to iterate over vals > 0.02which is not a sequence. If you are trying to filter just something> 0.02do:[x for x in vals if x > 0.02]

+2
source

You also have another problem (except for the missing one, if x> 0.02), you are comparing a list of strings with a float.

So you probably want [x for x in vals if x > '0.02']

I tested that this will give you the expected behavior. ['324', '0.23432']

+1
source

Source: https://habr.com/ru/post/1792688/


All Articles