简体   繁体   中英

How can i fix my code so a float be iterable?

for spamicities in sorted(map(lambda body: self.word_spamicity(body),re.sub("[^\w]", " ",  body).split())
                                ,key=lambda x: abs(0.5 - x),reverse=True)[0:38]:
 hamicities = map(lambda x: 1-x, spamicities)

spamicities is a float and i got an error TypeError: 'float' object is not iterable

How can i fix my code?

This will fail:

spamicities = 1.0
hamicities = map(lambda x: 1-x, spamicities)

map only works on lists. So if you want to use map , put your float into a list:

spamicities = [1.0]
hamicities = map(lambda x: 1-x, spamicities)  # returns [0.0]

A more conventional example (multiple list values):

spamicities = [1.0, 2.0, 3.0, 20.0]
hamicities = map(lambda x: 1-x, spamicities)  # returns [0.0, -1.0, -2.0, -19.0]

i updated my question with the complete code

Get rid of your for-loop, as its iterating over your list returned by sorted and giving you one float at a time. You want the entire list like so:

spamicities = sorted(map(lambda body: self.word_spamicity(body),re.sub("[^\w]", " ",  body).split()),key=lambda x: abs(0.5 - x),reverse=True)[0:38]
hamicities = map(lambda x: 1-x, spamicities)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM