Меню

Cannot unpack non iterable int object ошибка

Often when working on a data analytics project it requires you to split data out into its constituent parts.

There are a number of reasons for this, it can be confusing when you get errors as with the title of this post.

Before we explain this error and what it means, lets us first explain unpacking

Unpacking basically means splitting something up into a number of its parts that make it up.

To demonstrate if you take a,b,c = 123, and look to unpack it, it throws out the error, but why?

Well pure and simple, we have three values on the left “a,b,c”, looking for three values on the right.

a,b,c = 123
print(a)

Output:
 a,b,c = 123
TypeError: cannot unpack non-iterable int object

If you would like to fix this problem change the right hand side to have three values.

a,b,c = 1,2,3
print(a)
print(b)
print(c)
print(a,b,c)

Output:
1
2
3
1 2 3

Process finished with exit code 0

In essence, what is going on is that an evaluation checking that both sides have the same amount of values.

It is important to remember, the code above we used to show the error is an integer, which cannot be unpacked.

So if you take 123 for an example, which we used here it cannot be split into say 100 and 10 and 13.

In this case, even though when they are added up to 123, integers cannot be unpacked.

For this reason in the code for our solution, the difference is that the values used are tuples as follows:

a,b,c = 1,2,3
print(a)
print(b)
print(c)
print(a,b,c)
print(type((a,b,c)))

Or 
a,b,c = (1,2,3)
print(a)
print(b)
print(c)
print(a,b,c)
print(type((a,b,c)))

yield the same result:

1
2
3
1 2 3
<class 'tuple'>

Process finished with exit code 0

So in summary:

When unpacking there are a number of things to remember:

  • Integers on their own cannot be unpacked.
  • You need to make sure that if you have a number of variables, that you have the same number of integers if they the values.
    • This will make it a tuple and unpacking can then happen.

How can I solve this error After running my code as follows . I am using the function below and implementin running window for loop on it but end up getting the error below. The for loop works and hungs at a point.

def get_grps(s, thresh=-1, Nmin=3):
    """
    Nmin : int > 0
    Min number of consecutive values below threshold.
    """
    m = np.logical_and.reduce([s.shift(-i).le(thresh) for i in range(Nmin)])
    if Nmin > 1:
        m = pd.Series(m, index=s.index).replace({False: np.NaN}).ffill(limit=Nmin - 1).fillna(False)
    else:
        m = pd.Series(m, index=s.index)

    # Form consecutive groups
    gps = m.ne(m.shift(1)).cumsum().where(m)

    # Return None if no groups, else the aggregations
    if gps.isnull().all():
        return 0
    else:
        agg = s.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
        # agg2 = s2.groupby(gps).agg([list, sum, 'size']).reset_index(drop=True)
        return agg, gps


data_spi = [-0.32361498 -0.5229471   0.15702732  0.28753752   -0.01069884 -0.8163699
  -1.3169327   0.4413181   0.75815576  1.3858147   0.49990863-0.06357133
-0.78432    -0.95337325 -1.663739    0.18965477  0.81183237   0.8360347
  0.99537593 -0.12197364 -0.31432647 -2.0865853   0.2084263    0.13332903
 -0.05270813 -1.0090573  -1.6578217  -1.2969246  -0.70916456   0.70059913
 -1.2127264  -0.659762   -1.1612778  -2.1216285  -0.8054617    -0.6293912
 -2.2103117  -1.9373081  -2.530625   -2.4089663  -1.950846    -1.6129876]
lon = data_spi.lon
lat = data_spi.lat
print(len(data_spi))

n=6

for x in range(len(lat)):
    for y in range(len(lon)):
        if data_spi[0, x, y] != 0:
            for i in range(len(data_spi)-70):
                ts = data_spi[i:i+10, x, y].fillna(1)
                print(ts)
                # print(np.array(ts))

                agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)

                duration = np.nanmean(agg['sum'])
                frequency = len(agg['sum'])
                severity = np.abs(np.mean(agg['sum']))
                intensity = np.mean(np.abs(agg['sum'] / agg['size']))
                print(f'intensity {intensity}')

I get this error

 Traceback (most recent call last):
 File "/Users/mada0007/PycharmProjects/Research_ass /FREQ_MEAN_INT_DUR_CORR.py", line 80, in <module>
 agg, gps = get_grps(pd.Series(ts), thresh=-1, Nmin=3)
 typeError: cannot unpack non-iterable int object

How can I resolve this error?

Wondering today I will fix cannot unpack non-iterable int object Python sequence can be unpacked. So, let’s go and started.

Contents

  • 1 Fix Cannot Unpack Non-Iterable Int Object
    • 1.1 Explanation
      • 1.1.1 Example:
      • 1.1.2 1 Normal, biggest = calculate_statistics(purchases)
      • 1.1.3 Solution
    • 1.2 Cannot unpack non-iterable int object django
    • 1.3 Cannot unpack non-iterable nonetype object

There is an issue with the way you’re trying to unpack your object. Your program must have values that can be iterated, or else it won’t work!

This implies you can dole out the substance of an arrangement to different factors.

In the event that you attempt to unload a None worth utilizing this sentence structure, you’ll experience the “TypeError: can’t unload non-iterable NoneType object” error.

Explanation

Unpacking syntax allows you to allocate numerous factors simultaneously dependent on the substance of a succession.

Think about the accompanying code:

fruit_sales = [230, 310, 219]
Avocado, bananas, apples = fruit_sales

This code allows us to dole out the qualities in the fruit_sales variable to three separate factors.

The worth of “avocado” becomes 230, the worth of “bananas” gets 310, and the worth of “apples” gets 219.

The unloading language structure just deals with successions, similar to records and tuples.

You can’t unload a None worth since None qualities are not successions.

This mistake is ordinarily raised in the event that you attempt to unload the consequence of a capacity that does exclude a bring proclamation back.

Example:

We will make a program that ascertains the normal price tag at a bistro and the biggest buy made on a given day.

Start by characterizing a rundown of buys made on a specific day:

Buys = [2.30, 3.90, 4.60, 7.80, 2.20, 2.40, 8.30]

Then, characterize a capacity.

This capacity will compute the normal price tag and the biggest buy made on a given day:

def calculate_statistics(purchases):
	average_purchase = int(sum(purchases)) / int(len(purchases))
	largest_purchase = max(purchases)
	print("The normal buy was ${}.".format(round(average_purchase, 2)))
	print("The biggest buy was ${}.".format(round(largest_purchase, 2)))
	return average_purchase

print(calculate_statistics(Buys))

To ascertain the normal worth of a buy, partition the absolute worth of all buys by the number of buys are made on a given day.

We utilize the maximum() capacity to track down the biggest buy.

Since we’ve characterized our capacity, we can call it.

We relegate the qualities our capacity gets back to factors:

1 Normal, biggest = calculate_statistics(purchases)

We utilize the unloading language structure to get to these two qualities from our capacity.

This code allows us to get to the qualities our capacity returns in our principle program.

Since we approach these qualities outside our capacity, we print them to the control center:

print("The normal buy was ${}.".format(round(average_purchase, 2)))
print("The biggest buy was ${}.".format(round(largest_purchase, 2)))

Our code will show us the normal buy esteem and the worth of the biggest buy on the control center.

We round both of these qualities to two decimal spots utilizing the round() strategy.

We should run our program and see what occurs:

Our code returns an error message.

Solution

The error happens on the line where we attempt to unload the qualities from our capacity.

Our Error message reveals to us we’re attempting to unload values from a None worth.

This discloses to us our capacity isn’t returning the right qualities.

In the event that we investigate our capacity, we see we’ve failed to remember a bring proclamation back.

This implies our code can’t unload any qualities.

To settle this mistake, we should return the “average_purchase” and “largest_purchase” values in our capacity so we can unload them in our principle program:

def calculate_statistics(purchases):

average_purchase = int(sum(purchases)) / int(len(purchases))
largest_purchase = max(purchases)
return average_purchase

Let’s run our code

The average purchase was $4.5.

The largest purchase was $8.3.

Our code tells us the average purchase was $4.50 and the largest purchase was $8.30.

Read More: How to comment out multiple lines in python?

Cannot unpack non-iterable int object django

This means that Django is not able to unpickle the object because it is not an iterator. Most likely, this is because you are trying to unpack a list or string into an int object. To fix this, try casting the list or string into an int object before unpacking it.

Cannot unpack non-iterable nonetype object

This means that Python is unable to understand the data you are trying to unpack. This can happen for a number of reasons, but usually, it means that there is something wrong with the data itself (for example, it might be incomplete or corrupted).

If you’re getting this error message, it’s best to try and troubleshoot the problem by checking your data for errors and fixing them if possible. If you’re not sure how to do that, you might want to reach out for help from someone more experienced with Python.

I’m working on a mesh grid assignment that has a cursor that moves when you enter the assigned number. I was able to get the cursor to move, the only problem I’m having is that I want it to print out the location of the updated coordinates as the cursor moves, (ex. if the cursor moves down one block the new location should be (0,1)). I was messing around with last loop trying to get the coordinates to update and now I have the TypeError code in the #main program.

x = y = 0
size = int(input('Enter grid size: '))
print(f'Current location: ({x},{y})')

def show_grid(x, y):
	for i in range(size):
		for j in range(size):
			if i == y and j == x:
				print('+', end=' ')
			else:
				print('.', end=' ')
		print()
show_grid(x,y)

def show_menu():
	print('-- Navigation --')
	print('2 : Down')
	print('8 : Up')
	print('6 : Right')
	print('4 : Left')
	print('5 : Reset')
	print('0 : EXIT')
	return 0
show_menu()

choice = int(input('Enter an option: '))			#### current location not updating ####
cho = choice
def move(x, y, choice):
	if choice == 2:		# down
		show_grid(x, y+1)
	elif choice == 8:	# up
		show_grid(x, y-1)
	elif choice == 4:	# left
		show_grid(x-1, y)
	elif choice == 6:	# right
		show_grid(x+1, y)
	elif choice == 5:	# reset to (0,0)
		show_grid(x, y)
	elif choice == 1:
		print(choice, 'Not a valid input. Try again.')
		show_grid(x, y)
	elif choice == 3:
		print(choice, 'Not a valid input. Try again.')
		show_grid(x, y)
	elif choice == 7:
		print(choice, 'Not a valid input. Try again.')
		show_grid(x, y)
	elif choice == 9:
		print(choice, 'Not a valid input. Try again.')
		show_grid(x, y)
	return 0
move(x, y, choice)


#main program
while True:
	choice = show_menu()
	if cho == 0:
		print(f'Current location: ({x},{y})')
		break 				#Exit
	else:
		x, y = move(x, y, choice) ######<----TypeError: cannot unpack non-iterable int object
	print(f'Current location: ({x},{y})')
	if 0 <= x < size and 0 <= y < size: 	#inside the board
		print(f'Current location: ({x},{y})')
	else: 				#outside the board					                          
		print('The new location is off the board.')
		break
	print('Exit the program')

25.07.2019, 16:00. Показов 23579. Ответов 6


Добрый день
Вот код

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# -*- coding: utf-8 -*-
"""
This Example will show you how to use register_next_step handler.
"""
import constants
#!/usr/bin/python
 
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
import sqlite3
import telebot
import constants
from telebot import types
 
#Подключение к базе
conn = sqlite3.connect('my.sqlite',check_same_thread=False )
#Создание курсора
c = conn.cursor()
#Функция занесения пользователя в базу
def add_user(userid,username,usersurname,userage):
    c.execute("INSERT INTO users (id,name,surname,aage) VALUES ('%s','%s','%s','%s')"%(userid,username,usersurname,userage))
    conn.commit()
#Вводим данные
id = ''
name = ''
surname = ''
age = ''
print('n')
#Делаем запрос в базу
print("Список пользователей:n")
 
c.execute('SELECT * FROM users')
row = c.fetchone()
#выводим список пользователей в цикле
while row is not None:
   print("id:"+str(row[0])+" Логин: "+row[1]+" | Пароль: "+row[2])
   row = c.fetchone()
 
 
 
 
 
API_TOKEN = constants.token
 
bot = telebot.TeleBot(API_TOKEN)
 
@bot.message_handler(commands=['commands'])
def send_welcome(message):
    bot.send_message(message.from_user.id, """
---- n
     all commands n
     - /help n
     - /start n
     - /reg n
----
    """)
 
# Handle '/start' and '/help'
@bot.message_handler(commands=['help'])
def send_welcome(message):
    bot.reply_to(message, """
    Hi, I'm healthy lifestyle bot. I help you to find any coaches & partners for your training""")
 
@bot.message_handler(commands=['start'])
def handle_start(message):
    c.execute("SELECT id, name, surname, aage FROM Users WHERE (id LIKE ?) ",
              (message.from_user.id,))
 
    for name, surname, aage in c.fetchone():
        print()
        print("Name: " + name)
        print("Surname: " + surname)
        print("Age: " + aage)
        print()
    user_markup = telebot.types.ReplyKeyboardMarkup(True)
    user_markup.row('Поиск пары')
    user_markup.row('Найти тренера', '', '')
    user_markup.row('Ближайшая открытая тренировка')
    bot.send_message(message.from_user.id, "Добро пожаловать..", reply_markup=user_markup)
 
@bot.message_handler(content_types=['text'])
def start(message):
 
    if message.text == '/reg':
        keyboard = types.InlineKeyboardMarkup();  # наша клавиатура
        key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes1');  # кнопка «Да»
        keyboard.add(key_yes);  # добавляем кнопку в клавиатуру
        key_no = types.InlineKeyboardButton(text='Нет', callback_data='no1');
        keyboard.add(key_no);
        question = 'Хочешь изменить анкету?';
        bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
        bot.register_next_step_handler(message, get_name);
 
 
 
    else:
        bot.send_message(message.from_user.id, 'для посмотра комманд введите /commands');
 
def get_name(message): #получаем фамилию
    global name;
    name = message.text;
    bot.send_message(message.from_user.id, 'Какая у тебя фамилия?');
    bot.register_next_step_handler(message, get_surname);
 
def get_surname(message):
    global surname;
    surname = message.text;
    bot.send_message(message.from_user.id, 'Сколько тебе лет?');
    bot.register_next_step_handler(message, get_age);
 
def get_age(message):
    global age;
    while age == 0: #проверяем что возраст изменился
        try:
             age = int(message.text) #проверяем, что возраст введен корректно
        except Exception:
             bot.send_message(message.from_user.id, 'Цифрами, пожалуйста');
             break;
    age = int(message.text)
    id = message.from_user.id
    add_user(id, name, surname, age)
    # закрываем соединение с базой
    c.close()
    conn.close()
    keyboard = types.InlineKeyboardMarkup();  # наша клавиатура
    key_yes = types.InlineKeyboardButton(text='Да', callback_data='yes');  # кнопка «Да»
    keyboard.add(key_yes);  # добавляем кнопку в клавиатуру
    key_no = types.InlineKeyboardButton(text='Нет', callback_data='no');
    keyboard.add(key_no);
    question = 'Тебе ' + str(age) + ' лет, тебя зовут ' + name + ' ' + surname + '?';
    bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)
 
@bot.callback_query_handler(func=lambda call: True)
def callback_worker(call):
    if call.data == "yes": #call.data это callback_data, которую мы указали при объявлении кнопки
         #код сохранения данных, или их обработки
        bot.send_message(call.message.chat.id, 'Запомню : )');
        key = telebot.types.ReplyKeyboardMarkup(True, False)
        key.row('1', '2')
        key.row("6", "7",)
 
        key.row('Back')
        send = bot.send_message(call.message.chat.id, '...', reply_markup=key);
 
    elif call.data == "no":
 
        bot.send_message(call.message.chat.id, 'Мне пофиг, будешь ' + name + ' ' + surname);
    if call.data == "yes1":  # call.data это callback_data, которую мы указали при объявлении кнопки
        bot.send_message(call.from_user.id, 'Как вас зовут?');
 
 
 
    elif call.data == "no1":
 
        bot.send_message(call.message.chat.id, 'Хорошо ' + name + ' ' + surname);
 
 
bot.polling(none_stop=True, interva

Вот ошибка
2019-07-25 15:52:53,639 (util.py:65 WorkerThread1) ERROR — TeleBot: «TypeError occurred, args=(‘cannot unpack non-iterable int object’,)
Traceback (most recent call last):
File «C:UserstihonAppDataLocalProgramsPythonPyth on37-32libsite-packagestelebotutil.py», line 59, in run
task(*args, **kwargs)
File «C:/Users/tihon/PycharmProjects/TelBotRESET/main.py», line 69, in handle_start
for name, surname, aage in c.fetchone():
TypeError: cannot unpack non-iterable int object
«
Traceback (most recent call last):
File «C:/Users/tihon/PycharmProjects/TelBotRESET/main.py», line 158, in <module>
bot.polling(none_stop=True, interval=0)
File «C:UserstihonAppDataLocalProgramsPythonPyth on37-32libsite-packagestelebot__init__.py», line 389, in polling
self.__threaded_polling(none_stop, interval, timeout)
File «C:UserstihonAppDataLocalProgramsPythonPyth on37-32libsite-packagestelebot__init__.py», line 413, in __threaded_polling
self.worker_pool.raise_exceptions()
File «C:UserstihonAppDataLocalProgramsPythonPyth on37-32libsite-packagestelebotutil.py», line 108, in raise_exceptions
six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
File «C:UserstihonAppDataLocalProgramsPythonPyth on37-32libsite-packagessix.py», line 693, in reraise
raise value
File «C:UserstihonAppDataLocalProgramsPythonPyth on37-32libsite-packagestelebotutil.py», line 59, in run
task(*args, **kwargs)
File «C:/Users/tihon/PycharmProjects/TelBotRESET/main.py», line 69, in handle_start
for name, surname, aage in c.fetchone():
TypeError: cannot unpack non-iterable int object

Помогите плз

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



У меня проблемы. Буду очень признателен, если кто-нибудь поможет мне.

Это код:

def next1(n1, r1, c1, grid1):
    p_x, p_y = 0 # >>> TypeError: cannot unpack non-iterable int object
    for i in range(0, n1):
        for x in range(0, n1):
            if grid1[i][x] == "p":
                p_x = i
                p_y = x
    diff_x = abs(r1-p_x)
    diff_y = abs(c1-p_y)
    if diff_x > diff_y:
        if r1-p_x > 0:
            return "UP"
        else:
            return"DOWN"
    else:
        if c1-p_y > 0:
            return"LEFT"
        else:
            return"RIGHT"


n = int(input())
r, c = [int(i) for i in input().strip().split()]
grid = []
for i in range(0, n):
    grid.append(list(input()))
grid[r][c] = "m"
print(next1(n, r, c, grid)) # >>> TypeError: cannot unpack non-iterable int object

Это точная ошибка:

    Traceback (most recent call last):
      File "C:/Users/DELL/PycharmProjects/start/bot.py", line 28, in <module>
        print(next1(n, r, c, grid))<br/>
      File "C:/Users/DELL/PycharmProjects/start/bot.py", line 2, in next1
        p_x, p_y = 0
    TypeError: cannot unpack non-iterable int object

Как я могу устранить эту ошибку?

2 ответа

Лучший ответ

Вместо этого попробуйте px = py = 0 в этой строке (или просто определите эти значения в отдельных операторах)


2

Andbdrew
29 Мар 2020 в 15:59

Ваша строка p_x, p_y = 0 пытается распаковать с правой стороны значения = оператора 2 и назначить с левой стороны, это будет работать, если у вас есть список или кортеж, вы можете использовать:

p_x, p_y = 0, 0

Таким образом p_x и p_y будут равны 0


2

kederrac
29 Мар 2020 в 16:01

I got this problem.

[ ] 0/45, elapsed: 0s, ETA:Traceback (most recent call last):
File «tools/train.py», line 180, in
main()
File «tools/train.py», line 176, in main
meta=meta)
File «/home/maruyama/mmsegmentation/mmseg/apis/train.py», line 120, in train_segmentor
runner.run(data_loaders, cfg.workflow)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/runner/iter_based_runner.py», line 133, in run
iter_runner(iter_loaders[i], **kwargs)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/runner/iter_based_runner.py», line 66, in train
self.call_hook(‘after_train_iter’)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/runner/base_runner.py», line 307, in call_hook
getattr(hook, fn_name)(self)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/runner/hooks/evaluation.py», line 232, in after_train_iter
self._do_evaluate(runner)
File «/home/maruyama/mmsegmentation/mmseg/core/evaluation/eval_hooks.py», line 50, in _do_evaluate
runner.model, self.dataloader, show=False, pre_eval=self.pre_eval)
File «/home/maruyama/mmsegmentation/mmseg/apis/test.py», line 91, in single_gpu_test
result = model(return_loss=False, **data)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/torch/nn/modules/module.py», line 722, in _call_impl
result = self.forward(*input, **kwargs)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/parallel/data_parallel.py», line 42, in forward
return super().forward(*inputs, **kwargs)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/torch/nn/parallel/data_parallel.py», line 153, in forward
return self.module(*inputs[0], **kwargs[0])
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/torch/nn/modules/module.py», line 722, in _call_impl
result = self.forward(*input, **kwargs)
File «/home/maruyama/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/mmcv/runner/fp16_utils.py», line 128, in new_func
output = old_func(*new_args, **new_kwargs)
File «/home/maruyama/mmsegmentation/mmseg/models/segmentors/base.py», line 110, in forward
return self.forward_test(img, img_metas, **kwargs)
File «/home/maruyama/mmsegmentation/mmseg/models/segmentors/base.py», line 92, in forward_test
return self.simple_test(imgs[0], img_metas[0], **kwargs)
File «/home/maruyama/mmsegmentation/mmseg/models/segmentors/encoder_decoder.py», line 256, in simple_test
seg_logit = self.inference(img, img_meta, rescale)
File «/home/maruyama/mmsegmentation/mmseg/models/segmentors/encoder_decoder.py», line 239, in inference
seg_logit = self.slide_inference(img, img_meta, rescale)
File «/home/maruyama/mmsegmentation/mmseg/models/segmentors/encoder_decoder.py», line 162, in slide_inference
h_stride, w_stride = self.test_cfg.stride
TypeError: cannot unpack non-iterable int object

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Cannot resolve symbol string java ошибка
  • Cannot resolve symbol java intellij idea ошибка