Typeerror float object is not iterable что за ошибка
Перейти к содержимому

Typeerror float object is not iterable что за ошибка

  • автор:

TypeError: ‘x’ is not iterable (Тип ошибки ‘x’ не является итерационным)

Значение, которое даётся как правая сторона for. of или как аргумент функции, такой как Promise.all или TypedArray.from (en-US), не является итерационным объектом. Повторяемое может быть, встроенный итератор типа, такие как Array , String или Map (en-US), генератор результатом, или объект, реализующий итератор протокол.

Примеры

Итерация по свойствам объекта

В JavaScript, object не повторяется, если они реализуют итерационный протокол . Поэтому нельзя использовать for. of для перебора свойств объекта.

var obj =  France: "Paris", England: "London" >; for (let p of obj)  // TypeError: obj не является итерационным // … > 

Вместо этого вы должны использовать Object.keys или Object.entries , для итерации по свойствам или записям объекта.

var obj =  France: "Paris", England: "London" >; // Iterate over the property names: for (let country of Object.keys(obj))  var capital = obj[country]; console.log(country, capital); > for (const [country, capital] of Object.entries(obj)) console.log(country, capital); 

Другим вариантом для этого варианта использования может быть использование Map (en-US):

var map = new Map(); map.set("France", "Paris"); map.set("England", "London"); // Iterate over the property names: for (let country of map.keys())  let capital = map[country]; console.log(country, capital); > for (let capital of map.values()) console.log(capital); for (const [country, capital] of map.entries()) console.log(country, capital); 

Итерация по генератору

Генераторы — это функции, вызываемые для создания итерационного объекта.

function* generate(a, b)  yield a; yield b; > for (let x of generate) // TypeError: генерация не является итерационной console.log(x); 

Если они не вызываются, то объект Function , соответствующий генератору, можно вызвать, но нельзя выполнить итерацию. Вызов генератора создаёт итерационный объект, который будет выполнять итерацию по значениям, полученным во время выполнения генератора.

function* generate(a, b)  yield a; yield b; > for (let x of generate(1, 2)) console.log(x); 

Смотрите также

Found a content problem with this page?

  • Edit the page on GitHub.
  • Report the content issue.
  • View the source on GitHub.

This page was last modified on 7 авг. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Как исправить ошибку «TypeError: ‘float’ object is not iterable»

Мне необходимо написать программу, которая открывает файл, считывает данные и производит над ними операции. При отладке появилась ошибка:

«TypeError: ‘float’ object is not iterable».

Не могу понять с чем она связана и как ее решить. Сама ошибка представлена на скриншоте https://i.stack.imgur.com/NuFwt.png

Код программы:

class File(): # в классе происходит обработка данных из файла и необходимые для работы вычисления def __init__(self): print('в классе') def FILE(self):#построчное чтение из файла self.y = [] self.t1 =[] self.t2 =[] self.x = [] self.y1 = [] self.input_file = easygui.fileopenbox(filetypes=["*.docx"]) self.f = open (self.input_file) nenado = '---end of log file---' for i in range (2): self.f.readline() for line in self.f: if nenado in line: break else: a = line[1:6] b = line[7:12] time = line[25:32] self.t1.append(float(a)) self.t2.append(float(b)) self.x.append(float(time)) self.f.close() def rasschet_ΔTy(self):#график из файла self.y = [self.t2 - self.t1 for self.t1, self.t2 in zip(self.t1, self.t2)] return self.y def rasschet_x(self):#ось времени self.x = [z/60 for z in self.x] return self.x def rasschet_ΔTy1(self):# график смещенный в 0 self.k = self.t2[0] - self.t1[0] self.rasschet_ΔTy() self.y1 =[g - self.k for g in self.y] return self.y1 def rasschet_filtr_ΔTy(self):# цифровой фильтр для графика из файла self.yhat = savgol_filter(self.rasschet_ΔTy(), 251, 3) return self.yhat def rasschet_filtr_ΔTy1(self):# цифровой фильтр для графика смещенного в 0 self.yhat1 = savgol_filter(self.rasschet_ΔTy1(), 251, 3) return self.yhat1 a = File() def demo(): a.FILE() demo() def Demo():#для проверки print(a.rasschet_ΔTy1()) print(a.rasschet_ΔTy()) print(a.rasschet_x()) Demo() 

How to Fix TypeError in Python: NoneType Object Is Not Iterable

How to Fix TypeError in Python: NoneType Object Is Not Iterable

The Python TypeError: NoneType Object Is Not Iterable is an exception that occurs when trying to iterate over a None value. Since in Python, only objects with a value can be iterated over, iterating over a None object raises the TypeError: NoneType Object Is Not Iterable exception.

What Causes TypeError: NoneType Object Is Not Iterable

For an object to be iterable in Python, it must contain a value. Therefore, trying to iterate over a None value raises the Python TypeError: NoneType Object Is Not Iterable exception. Some of the most common sources of None values are:

  • Calling a function that does not return anything.
  • Calling a function that sets the value of the data to None .
  • Setting a variable to None explicitly.

Python TypeError: NoneType Object Is Not Iterable Example

Here’s an example of a Python TypeError: NoneType Object Is Not Iterable thrown when trying iterate over a None value:

mylist = None for x in mylist: print(x) 

In the above example, mylist is attempted to be added to be iterated over. Since the value of mylist is None , iterating over it raises a TypeError: NoneType Object Is Not Iterable :

Traceback (most recent call last): File "test.py", line 3, in for x in mylist: TypeError: 'NoneType' object is not iterable 

How to Fix TypeError in Python: NoneType Object Is Not Iterable

The Python TypeError: NoneType Object Is Not Iterable error can be avoided by checking if a value is None or not before iterating over it. This can help ensure that only objects that have a value are iterated over, which avoids the error.

Using the above approach, a check can be added to the earlier example:

mylist = None if mylist is not None: for x in mylist: print(x) 

Here, a check is performed to ensure that mylist is not None before it is iterated over, which helps avoid the error.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

How to fix TypeError: ‘float’ object is not iterable

Posted on Feb 27, 2023

One error that you might encounter when coding in Python is:

  1. Using a float in a for loop
  2. Call list() with float objects
  3. Call the sum() function and pass float objects

This tutorial shows you examples that cause this error and how to fix it.

1. Using a float in a for loop

One common cause of this error is when you pass a float when attempting to iterate using a for loop.

Suppose you have a for loop code as follows:

The num variable is a float object, so it’s not iterable and causes the following error when used in a for loop:

A for loop requires you to pass an iterable object, such as a list or a range object.

If you want to use a float, you need to convert it to an int using the int() function, then convert it to a range with range() as follows:

 Output:
Unlike the for loop in other programming languages where you can use an integer value, the for loop in Python requires you to pass an iterable. Both int and float objects are not iterable.

2. Call list() with float objects

This error also occurs when you call the list() function and pass float objects to it.

Suppose you want to create a list from float values as follows:

Python shows “TypeError: ‘float’ object is not iterable” because you can’t pass a float when creating a list.

To create a list from a float, you need to surround the argument in square brackets:

The same error also occurs when you create a dictionary, tuple, or set using a float object. You need to use the appropriate syntax for each function:

For the dict() function, you need to pass arguments in the form of key=value for the key-value pair.

3. Call the sum() function and pass float objects

Another condition where this error might occur is when you call the sum() function and pass float objects to it.

Suppose you try to sum floating numbers as shown below:

You’ll get “float is not iterable” error because the sum() function expects a list.

To fix this, surround the arguments you passed to sum() with square brackets as follows:

Notice how the sum function works without any error this time.

Conclusion

The Python error “‘float’ object is not iterable” occurs when you pass a float object when an iterable is expected.

To fix this error, you need to correct the assignments in your code so that you don’t pass a float in place of an iterable, such as a list or a range.

If you’re using a float in a for loop, you can use the range() and int() functions to convert that float into a range. You can also convert a float into a list by adding square brackets [] around the float objects.

I hope this tutorial is helpful. Happy coding! ��

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Search

Type the keyword below and hit enter

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *