Как исправить ошибку NoneType object is not iterable?
Задача:
Сгенерировать десять списков из случайных чисел. Вывести их и сумму их элементов на экран. Найти среди них один с максимальной суммой элементов. Указать какой он по счету, повторно вывести этот список и сумму его элементов. Заполнение списка и подсчет суммы его элементов оформить в виде отдельных функций. Ошибка:
Traceback (most recent call last): File "C:\Python34\5.16.py", line 20, in g = max(d) TypeError: 'NoneType' object is not iterable
import random n = int(input("Введите кол-во возможных случайных:")) b = int(input("Введите диапазон случайных значений:")) def func_1(n,b): d = [[random.randrange(b) for i in range(n)] for i in range(10)] print("Исходные 10 списков:",d) func_1(n,b) def func_2(n,b): d = [[sum(random.randrange(b) for i in range(n))] for i in range(10)] print("сумма элементов в каждом из 10 списков:",d) func_2(n,b) d = func_2(n,b) g = max(d) print("Максимальная сумма элементов:",g)
Форум русскоязычного сообщества Ubuntu
Страница сгенерирована за 0.033 секунд. Запросов: 25.
- Сайт
- Об Ubuntu
- Скачать Ubuntu
- Семейство Ubuntu
- Новости
- Форум
- Помощь
- Правила
- Документация
- Пользовательская документация
- Официальная документация
- Семейство Ubuntu
- Материалы для загрузки
- Совместимость с оборудованием
- RSS лента
- Сообщество
- Наши проекты
- Местные сообщества
- Перевод Ubuntu
- Тестирование
- RSS лента
© 2012 Ubuntu-ru — Русскоязычное сообщество Ubuntu Linux.
© 2012 Canonical Ltd. Ubuntu и Canonical являются зарегистрированными торговыми знаками Canonical Ltd.
Ошибка ‘NoneType’ object is not iterable в программе ‘Phyton’

Программа проходит все тесты в codewars, но на заключительном этапе выдает следующую ошибку:
Кликните здесь для просмотра всего текста
Traceback (most recent call last):
File «/workspace/default/.venv/lib/python3.10/site-packages/codewars_test/test_framework.py», line 112, in wrapper
func()
File «/workspace/default/tests.py», line 21, in fixed_tests
test.assert_equals(remove_rotten(tst[0]), tst[1], f»Input = «)
File «/workspace/default/solution.py», line 4, in remove_rotten
bag_of_fruits = [x.replace(‘rotten’, ») for x in bag_of_fruits]
TypeError: ‘NoneType’ object is not iterable
Чего они вообще хотят?
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Ошибка cannot unpack non-iterable nonetype object
import pyautogui from PIL import Image from time import sleep pyautogui.FIALSAFE = True.
NoneType object is not iterable
Добрый вечер! Выдаёт ошибку: "for i, num in enumerate(nums): TypeError: ‘NoneType’ object is not.

NoneType’ object is not iterable
numbers = lst= for i in numbers: lst1.append(i) for j in range(i): if j // 2.
‘NoneType’ object is not iterable Что делать?
Как исправить эту ошибку? import json import requests from bs4 import BeautifulSoup .
![]()
5898 / 3355 / 1035
Регистрация: 03.11.2009
Сообщений: 10,003
1 2 3 4
def remove_rotten(bag_of_fruits): if not bag_of_fruits: return [] return [x.replace('rotten', '').lower() for x in bag_of_fruits]
![]()
2689 / 1595 / 513
Регистрация: 21.02.2017
Сообщений: 4,209
Записей в блоге: 1
Jabbson,
def remove_rotten(bag_of_fruits): return [x.replace('rotten', '').lower() for x in bag_of_fruits] if bag_of_fruits else []
![]()
5898 / 3355 / 1035
Регистрация: 03.11.2009
Сообщений: 10,003
да я тоже видел
![]()
2689 / 1595 / 513
Регистрация: 21.02.2017
Сообщений: 4,209
Записей в блоге: 1
def remove_rotten(bag_of_fruits): return list(map(lambda x: x.replace("rotten", "").lower(), bag_of_fruits or []))
1390 / 531 / 67
Регистрация: 10.04.2009
Сообщений: 8,734
здравствуйте
код:
1 2 3 4 5 6 7 8 9
txt_htm = ('какой-то текст, большой и с абзацами') lst_htm = txt_htm.split('\n') print(f'len lst_htm: ') lst_htm = list(set(lst_htm)) print(f'len lst_htm: ') lst_htm = lst_htm.sort() print(f'lst_htm после sort():') for ind, val in enumerate(lst_htm): print(ind, val)
принты вывели:
len lst_htm: 183698
len lst_htm: 103534
получил ошибку:
for ind, val in enumerate(lst_htm):
^^^^^^^^^^^^^^^^^^
TypeError: ‘NoneType’ object is not iterable
грешу, что первое значение будет «» и что это меняет?
должно вывести
0
1 второе значение
поясните плиз
Добавлено через 1 час 6 минут
Сообщение от Ципихович Эндрю 
грешу, что первое значение будет «» и что это меняет?
так и есть
1 2 3
print(lst_htm[0]) ~~~~~~~^^^ TypeError: 'NoneType' object is not subscriptable
какое-то светопредставление.
456 / 298 / 131
Регистрация: 16.02.2021
Сообщений: 567
Сообщение от Ципихович Эндрю 
какое-то светопредставление.
ничего удивительного,
это значит метод sort возвращает None,
можно сделать так
1 2 3 4 5 6 7 8 9 10
txt_htm = ('какой-то текст, большой и с абзацами') lst_htm = txt_htm.split('\n') print(f'len lst_htm: ') lst_htm = list(set(lst_htm)) print(f'len lst_htm: ') lst_htm.sort() #или lst_htm = sorted(lst_htm) print(f'lst_htm после sort():') print(lst_htm) for ind, val in enumerate(lst_htm): print(ind, val)
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь
Ошибка в коде ‘NoneType’ object is not iterable
from autopy import * from time import * def mouse_click(s): if s == 1: .
TypeError: ‘NoneType’ object is not iterable
Сначала стоял Python 3.8.1 на который без проблем установился opencv, но по необходимости нужен был.
TypeError: ‘NoneType’ object is not iterable
Здравствуйте уважаемые программисты и знатоки. Есть сама программа "Калькулятор валютных свопов" в.

Python | Ошибка «TypeError: ‘NoneType’ object is not iterable»
Добрый день всем! Реализую алгоритм линейного поиска на Python с замером времени, симулируя.

Ошибка object is not iterable
a = input count = 1 for i in a: if i == " ": count += 1 print(count) Почему.
ошибка for j in x: ‘int’ object is not iterable
вылетает такая ошибка "for j in x: ‘int’ object is not iterable" на функцию def.
Или воспользуйтесь поиском по форуму:
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!