Valueerror not enough values to unpack expected 2 got 1

Valueerror not enough values to unpack expected 2 got 1

ValueError: not enough values to unpack (expected 2, got 1)

the following is my code

File «E:\p\lib\site-packages\django\core\handlers\exception.py» in inner 39. response = get_response(request)

File «E:\p\lib\site-packages\django\core\handlers\base.py» in _get_response 187. response = self.process_exception_by_middleware(e, request)

File «E:\p\lib\site-packages\django\core\handlers\base.py» in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File «F:\ddjj\x\mysite\medicine\views.py» in add 25. return render(request, ‘medicine/add.html’, <'form': form>,)

File «E:\p\lib\site-packages\django\shortcuts.py» in render 30. content = loader.render_to_string(template_name, context, request, using=using)

File «E:\p\lib\site-packages\django\template\loader.py» in render_to_string 68. return template.render(context, request)

File «E:\p\lib\site-packages\django\template\backends\django.py» in render 66. return self.template.render(context)

File «E:\p\lib\site-packages\django\template\base.py» in render 208. return self._render(context)

File «E:\p\lib\site-packages\django\template\base.py» in _render 199. return self.nodelist.render(context)

File «E:\p\lib\site-packages\django\template\base.py» in render 994. bit = node.render_annotated(context)

File «E:\p\lib\site-packages\django\template\base.py» in render_annotated 961. return self.render(context)

File «E:\p\lib\site-packages\django\template\loader_tags.py» in render 174. return compiled_parent._render(context)

File «E:\p\lib\site-packages\django\template\base.py» in _render 199. return self.nodelist.render(context)

File «E:\p\lib\site-packages\django\template\base.py» in render 994. bit = node.render_annotated(context)

File «E:\p\lib\site-packages\django\template\base.py» in render_annotated 961. return self.render(context)

File «E:\p\lib\site-packages\django\template\loader_tags.py» in render 70. result = block.nodelist.render(context)

File «E:\p\lib\site-packages\django\template\base.py» in render 994. bit = node.render_annotated(context)

File «E:\p\lib\site-packages\django\template\base.py» in render_annotated 961. return self.render(context)

File «E:\p\lib\site-packages\django\template\base.py» in render 1050. return render_value_in_context(output, context)

File «E:\p\lib\site-packages\django\template\base.py» in render_value_in_context 1028. value = force_text(value)

File «E:\p\lib\site-packages\django\utils\encoding.py» in force_text 76. s = six.text_type(s)

File «E:\p\lib\site-packages\django\utils\html.py» in 391. klass.str = lambda self: mark_safe(klass_str(self))

File «E:\p\lib\site-packages\django\forms\forms.py» in str 123. return self.as_table()

File «E:\p\lib\site-packages\django\forms\forms.py» in as_table 271. errors_on_separate_row=False)

File «E:\p\lib\site-packages\django\forms\forms.py» in _html_output 226. ‘field’: six.text_type(bf),

File «E:\p\lib\site-packages\django\utils\html.py» in 391. klass.str = lambda self: mark_safe(klass_str(self))

File «E:\p\lib\site-packages\django\forms\boundfield.py» in str 43. return self.as_widget()

File «E:\p\lib\site-packages\django\forms\boundfield.py» in as_widget 101. return force_text(widget.render(name, self.value(), attrs=attrs))

File «E:\p\lib\site-packages\django\forms\widgets.py» in render 537. options = self.render_options([value])

File «E:\p\lib\site-packages\django\forms\widgets.py» in render_options 560. for option_value, option_label in self.choices:

Exception Type: ValueError at /medicine/add/ Exception Value: not enough values to unpack (expected 2, got 1)

ValueError: not enough values to unpack (expected 2, got 1), Splitting string into two parts with split() didn’t work

For that I wrote a code:

Getting this error:

Edit: I wrote this:

Now I am getting this output:

How to store the 2nd part of the string to a var?

Edit1: I wrote this which solved my purpose (Thanks to Peter Wood):

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You don’t want to split on the «kg», because that means it’s not part of the actual data. Although looking at the docs, I see you can include them https://docs.python.org/3/howto/regex.html But the split pattern is intended to be a separater.

Here’s an example of just making a pattern for exactly what you want:

You need to use regex split rather than simple string split and the precise pattern you are looking for splitting is this,

Basically the point where is preceded by digit, hence this regex (? and followed by alphabets, hence this regex (?=[a-zA-Z]+) and it can be seen in this demo with pink marker.

Also, here is your modified Python code,

Also, if there can be optional space between the number and units, you can better use this regex which will optionally consume the space too during split,

Keep Getting ValueError: not enough values to unpack (expected 2, got 1) for a text file for sentiment analysis?

I am trying to turn this text file into a dictionary using the code below:

It keeps returning:

The data in the text file looks like this:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You are trying to split a text value at ‘-‘. And unpack it to two values (key (before the dash), value (after the dash)). However, some lines in your txt file do not contain a dash so there is not two values to unpack. Try checking for blank lines as this could be a cause of the issue.

Your code doesn’t match the error message. I’m going to assume that the error message is the correct one.

Keep getting ValueError: not enough values to unpack (expected 2, got 1) [closed]

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

I’m going through Kinder’s and Nelson book A Student’s Guide to Python for Physical Modeling. At the beginning of chapter 3 is information for downloading prepared data sets that can be used for practice. The data sets are in a zip file at press.princeton.edu/titles/10644.html. The data set I’m trying to use from the zip file is HIVseries.csv. The file contain 16 lines of code, as follows:

It is two columns of numbers separated by a comma. On pages 48 and 49, the book instructs me to load the data set and generate the data as an array with the following commands:

When I run these commands I keep getting the following error: ValueError: not enough values to unpack (expected 2, got 1)

a, b = map(int, input().split(‘ ‘)) ValueError: not enough values to unpack (expected 2, got 1)

Последовательность чисел a1, a2, …, ai,… называется Фибоначчиевой, если для всех i≥3 верно, что ai=ai–1+ai–2, то есть каждый член последовательности (начиная с третьего) равен сумме двух предыдущих. Ясно, что задавая различные числа a1 и a2 мы можем получать различные такие последовательности, и любая Фибоначчиева последовательность однозначно задается двумя своими первыми членами. Будем решать обратную задачу. Вам будет дано число N и два члена последовательности: aN и aN+1. Вам нужно написать программу, которая по их значениям найдет a1 и a2.

Входные данные Вводятся число N и значения двух членов последователности: aN и aN+1 (1≤N≤30, члены последовательности — целые числа, по модулю не превышающие 100) Если вы пишите на языке программирования python, то считывание aN и aN+1 элементов должно быть организовано так: x, y = map(int, input().split())

Выходные данные Выведите два числа — значения первого и второго членов этой последовательности.

Примеры входные данные 4 3 5 выходные данные 1 1

Не могу сделать код по заданному образцу строки Если вы пишите на языке программирования python, то считывание aN и aN+1 элементов должно быть организовано так: x, y = map(int, input().split())

написал прогу но выдает ошибку Вот сам код:

I got this error ValueError: not enough values to unpack (expected 2, got 1)

Python

Iam trying to extract frames from UCF-101 dataset, but I got this error: ValueError: not enough values to unpack (expected 2, got 1). Iam using Anaconda 1.7.2

This line shows the argument error: sequence_type, sequence_name = video_path.split(«.avi»)[0].split(«/»)[-2:]

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

1 Answer 1

Your responses to advice and questions in the comments suggest to me that this code is not really yours and you have no clear idea what this line

That is the reason why commenters asked you to show us the value you were trying to unpack, instead of just telling us about it. Programming problems are very often about tiny specific details. So, in the absence of an explicit response from you, this is still only a guess, but if the guess is correct, the line that is giving you the error should be

(note, you have to double the backslash) or, if you want to the code to be platform-independent,

ValueError: not enough values to unpack (expected 2, got 1) NetworkX python 3

The error reported

where, len(edge_labels) = 150

When i pass the edge labels dictionary inside nx.draw_networkx_edge_labels using «labels» argument instead of «edge_labels», it shows empty dictionaries as shown in picture. But i am looking for edge labels with key:value entries. Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

1 Answer 1

The documentation for draw_networkx_edge_labels states that the edge_labels argument requires a dictionary where the keys are tuples with two elements:

edge_labels (dictionary) – Edge labels in a dictionary keyed by edge two-tuple of text labels (default=None). Only labels for the keys in the dictionary are drawn.

Your keys are single strings.

The tuples represent edges; in your graph those are tuples of integers, listed in map_paths_reduced ; your label keys must match those edges.

Flask : ValueError: not enough values to unpack (expected 2, got 1)

I am a Newbee in Python, Flask and API, and trying to learn it with my own project.

The API I am querying requires Basic Authentication. Created a login.html and dashboard.html as templates of Flask. Created a module myclasses.py and the reporter.py which is the main module for Flask Views and other code.

login.html request user for IP, Username and Password which is captured in (/) view, and then forwarded to the Function defined in MyClasses.py using «call_api» to form the API and the function returns the Data.

Now I don’t know and not sure how to proceed with forwarding the received data as json to (/dashboard) view for parsing and displaying in Dashboard template page.

I am getting error, what does this means?

If I remove status_code, data, it works fine.

for sure, I am not doing it the right way in many areas of this code. Also, If you guys tell me on how to debug the code when flask is involved, I tried using breakpoints in PyCharm but code does not stops when I browse the templates.

Appreciate you help and Thank you for the time.

Not enough values to unpack(expected 2, got 1) using odeint [closed]

I have been trying to numerically solve the Rayleigh Plesset equation. I have written

However, when I run the code I found the following error: ValueError: not enough values to unpack (expected 2, got 1).

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

In this line of code;

You are attempting to set 2 variables in one line, however only providing one value.

You need to set 2 values or only assign one variable here.

R, u = y0, 1 as an example.

Ok. So I have passed in two variables to the equation, and the code looks like this:

»’ import numpy as np from matplotlib import pyplot as plt from scipy.integrate import odeint

However, when i run the code I get a a useless graph which doesn’t make any sense at all. I’ve used the parameters as defined here: https://people.eng.unimelb.edu.au/asho/AdvCompMech/Assignment_1.pdf

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python or ask your own question.

Related

Hot Network Questions

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

How to fix ValueError: not enough values to unpack (expected 3, got 1) in Python?

I would like to extract each value for further computation, and when I do the following code:

I am having this error:

How can I extract each value corresponding to my user, item, tag variables in the dataset?

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

if first_record only has these 3 elements you can directly assign variable as follows:

You’re trying to iterate over 1D list, hence the problem. You can convert it into a 2D list like so

Then you should be able to iterate

EDIT: As pointed out in the comment, if you’re using just record[0] then it’s best not to iterate, rather assign the values directly like so

ValueError: not enough values to unpack (expected 11, got 1)

I wrote a script for system automation, but I’m getting the error described in the title. My code below is the relevant portion of the script. What is the problem?

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

What are you splitting on? Looks like a CSV, so try

As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

The error message is fairly self-explanatory

To see what line is causing the issue, you could add some debug statements like this:

As Martin suggests, you might also be splitting on the wrong delimiter.

Looks like something is wrong with your data, it isn’t in the format you are expecting. It could be a new line character or a blank space in the data that is tinkering with your code.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python csv or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

I have a problem with my Python 3 program. I use Mac OS X. This code is running properly.

Problems starts when I am trying to add next value to the for loop.

Terminal shows error:

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You probably want to assign the lastname you are reading out here

to something; currently the program just forgets it

you could do that two lines after, like so

good news is, python can handle this

1. First should understand the error meaning

Error not enough values to unpack (expected 3, got 2) means:

a 2 part tuple, but assign to 3 values

and I have written demo code to show for you:

using VSCode debug effect:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2. For your code

but error ValueError: not enough values to unpack (expected 3, got 2)

so should change code to:

and better change to better syntax:

then everything is OK and clear.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

unpaidMembers.items() must have only two values per iteration.

Here is a small example to illustrate the problem:

This will fail, and is what your code does:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.

Python, ValueError: not enough values to unpack (expected 2, got 1), Python OOP

In this project, i was told to make a code where i should leverage the convenience of a dictionary to power a configuration file.

My following code looks like this:

The problem arises when i try to run the code, with the specified file name, An error of «ValueError: not enough values to unpack (expected 2, got 1)», from this line of code:

I have searched for solutions regarding this particular problem but have never seem to find it, and your help would really benefit me.

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

First, it would be great if you could share a few sample lines from your input file.

The reason you get the error is because line.split(‘=’, 1) is not returning two values ( key and value ). What solution to go for depends on what you intend to do with the file.

If you are expecting only 2 values, then keep the code as is and check your files. I see you already leverage the maxsplit argument, which determines the maximum times to split:

And if you have less, then you will get the error you cited above.

If you have some corrupt lines with only

not enough values to unpack (expected 4, got 1) within a funtion, python

I am new to python so I don’t understand the Error I keep getting. I hope someone can explain. If you need any more information I’ll edit it in.

email,fname,sname,password=line.split(«, «)#splits each line however creates an extra space between the lines because of enter

ValueError: not enough values to unpack (expected 4, got 1)

I want it print like this:

email@abc.org.uk Name Surname fakepassword

check@email.org.uk Z Y fakepassword

testing@the.program Ray Check hello

email,fname,sname,password=line.split(«\n»)#splits each line however creates an extra space between the lines because of enter

ValueError: not enough values to unpack (expected 4, got 2)

At least I got one more value XD

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Rather than re-implementing a csv reader, use the csv module from Python’s standard library.

Example copied from the documentation:

This shows the canonical way to read a CSV file. Note that the csv.reader yields a list of strings for each iteration, so you don’t have to split it.

You can test the length of the line before splitting it:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

The problem is your input. You need to make sure that each line in your input has all these 4 characteristics, and they are always delimited by a comma.

This error occurs when the number of values on the right side on the equation do not match the number of variables on the right side. An example would be:

The following works as the line is split into a list of 4 elements

But the following does not work

Django python ValueError: not enough values to unpack (expected 2, got 1)

I have this code to in my views.py that will export to excel, i combined two query in 1 loop but i receive this error Exception Type: ValueError at /export_reportF/ Exception Value: not enough values to unpack (expected 2, got 1)

this is the traceback Exception Type: ValueError at /export_reportF/ Exception Value: not enough values to unpack (expected 2, got 1)

1 Answer 1

What this gives you is a list which contains two lists. If you loop over it, it will loop twice, first giving you the reports list and then the daily list. Try this:

That should make the problem obvious. The solution is to replace line 3 with this:

Which will give you an iterable of pairs, where each pair has one report and one day in it.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

ValueError: not enough values to unpack (expected 4, got 1)

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

4 Answers 4

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Run it from the shell like this:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

You could run it like this: python script.py first, second, third

I think you are running the following command:

You are writing a program which is aksing for 4 inputs and you are giving onle one. That’s why you are receiving an error. You can use the below command:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python pycharm or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

ValueError: not enough values to unpack (expected 2, got 1) #6

Comments

MuruganR96 commented Nov 15, 2018 •

ValueError: all the input array dimensions except for the concatenation axis must match exactly
result = np.concatenate((result, label_to_center[id]))

again shows this error,

ValueError: not enough values to unpack (expected 2, got 1)

if numpy shape is an issue then it will resolve automatically using utills.py
but it can’t reach that utils.resize_sequence function.

train_total_length, observation_dim = train_sequence.shape
ValueError: not enough values to unpack (expected 2, got 1)

how to resolve this issue @wq2012 sir.
advance thanks

The text was updated successfully, but these errors were encountered:

wq2012 commented Nov 15, 2018

You are using the APIs in the wrong way.

I have updated the README.md with more detailed instructions.

For integration test, label_to_center should be a dict from string to 1-d vectors, not to numbers.

Also, you are not supposed to directly apply UIS-RNN to audio. Instead you should apply it on speaker discriminative embeddings like d-vectors.

MuruganR96 commented Nov 19, 2018 •

@wq2012 thank you.
how to pass d-vector embeddings?
i referered this paper and github repo,

but i was confused,

in this statement, where i am do this, D-vector training_sequence with UIS-RNN training.
because in this PyTorch_Speaker_Verification i was created TIMIT Dataset D-vectors embeedings.
but I don’t know how to process this D-vector embeddings into our UIS-RNN?.

sir please help me. thank you for advance response

wq2012 commented Nov 19, 2018

The reason that we concatenate is that we will be resampling training data and block-wise shuffling training data as a data augmentation process.

But yes, I admit this API is a little weird. We will change it in the future, as a long term plan.

About d-vectors embeddings, we are not responsible for any third-party implementations.

MuruganR96 commented Nov 19, 2018

thank you so much sir.
About d-vectors embeddings, we are not responsible for any third-party implementations

then how can i generated d-vectors embeddings? sir give me some hint how to construct d-vector embeddings? the above one is useful or not sir?

i think now i am very clear about uis-rnn api and then architecture as well as.

but i can’t move another step, because of that d-vector embeddings construct and intialize,

if u interested to help me, then give your suggestions sir.

thank you very much for your response sir.

wq2012 commented Nov 19, 2018

Glad that the UIS-RNN API is clear to you.

You can use any third-party implementation of d-vector embeddings, or similar techniques like x-vectors from JHU. But we are not responsible for the quality of them. You need to directly ask the authors of those libraries on how to use them.

Some of the libraries are only able to produce per-utterance d-vector embeddings, while for UIS-RNN, we require continuous d-vector embeddings (as sequences). We have no guarantee which third-party library supports this. You need to do your own research here.

This GitHub repo is for the UIS-RNN library only.

Footer

© 2022 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Keep getting ValueError: not enough values to unpack (expected 2, got 1) [closed]

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

I’m going through Kinder’s and Nelson book A Student’s Guide to Python for Physical Modeling. At the beginning of chapter 3 is information for downloading prepared data sets that can be used for practice. The data sets are in a zip file at press.princeton.edu/titles/10644.html. The data set I’m trying to use from the zip file is HIVseries.csv. The file contain 16 lines of code, as follows:

It is two columns of numbers separated by a comma. On pages 48 and 49, the book instructs me to load the data set and generate the data as an array with the following commands:

When I run these commands I keep getting the following error: ValueError: not enough values to unpack (expected 2, got 1)

ValueError: not enough values to unpack (expected 2, got 1) is keeping me from finishing my code

Hello i am trying to make a dictionary from a file in python and i keep getting this error. I have no idea how to fix it. Help would be much appreciated.

Here is my code:

And here is how the file looks like:

Thanks in advance

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

read will add an extra blank line when it hits the end of the file. To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string or bytes object. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string (»).

change your program to check if libe exists.

IMP: please do not use builtin name dict for a variable

lines = [line for line in row.split(«\n») if line]

In addition you shouldn’t reuse the builtin name dict for a variable. And you are using return outside a function, which is invalid.

Keep getting ValueError: not enough values to unpack (expected 2, got 1) [closed]

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

I’m going through Kinder’s and Nelson book A Student’s Guide to Python for Physical Modeling. At the beginning of chapter 3 is information for downloading prepared data sets that can be used for practice. The data sets are in a zip file at press.princeton.edu/titles/10644.html. The data set I’m trying to use from the zip file is HIVseries.csv. The file contain 16 lines of code, as follows:

It is two columns of numbers separated by a comma. On pages 48 and 49, the book instructs me to load the data set and generate the data as an array with the following commands:

When I run these commands I keep getting the following error: ValueError: not enough values to unpack (expected 2, got 1)

not enough values to unpack (expected 2, got 1) in python

I am getting the error below:

How can this be fixed?

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

So, you’re getting this error because the last line of your code is trying to split strings based on tab characters, but there aren’t any tab characters in your input.

If you print the value generated by the last line of the loop, rather than assigning it, you see that the right-hand side of the assignment contains a single string, whereas the word, count = code expects a tuple that will unpack to two values.

This gives, as output:

It’s unclear where you want the value of count to come from, so I can’t suggest a fix for that without a bit more information.

Pandas read_excel returning ‘not enough values to unpack (expected 2, got 1)’

My problem is pretty simple, I’m just trying to read a locally located excel file into a dataframe using pandas.

The xlsx file has multiple sheets, but I get the same «ValueError: not enough values to unpack (expected 2, got 1)» even when specifying sheetname.

Traceback (most recent call last):

File «», line 1, in pd.read_excel(filename)

File «C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py», line 200, in read_excel io = ExcelFile(io, engine=engine)

File «C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py», line 257, in init self.book = xlrd.open_workbook(io)

File «C:\ProgramData\Anaconda3\lib\site-packages\xlrd__init__.py», line 422, in open_workbook ragged_rows=ragged_rows,

File «C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py», line 833, in open_workbook_2007_xml x12sheet.process_stream(zflo, heading)

File «C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py», line 553, in own_process_stream self.do_merge_cell(elem)

File «C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py», line 609, in do_merge_cell first_cell_ref, last_cell_ref = ref.split(‘:’)

ValueError: not enough values to unpack (expected 2, got 1)

Edit: I created a new Excel file, and copied two of the tabs from the original file over to the new Excel file. Pandas read_excel worked with the new file. However, I want to be able to work from the original.

ValueError: not enough values to unpack (expected 2, got 1) Wrong

In the following code:

I am getting the error below:

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You can pave over anything that goes wrong and log it like this:

Make sure you are not passing any empty string to email. If email doesn’t contain @ the split will always return a single value. And you can’t unpack (or assign) a single value into two variables.

_, tmp = «random@gmail.com».split(«@», maxsplit=1) It works.

_, tmp = «randomemail».split(«@», maxsplit=1) It will throw error.

For more information about split method, see here: python-split

Not the answer you’re looking for? Browse other questions tagged python python-3.x or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

ValueError: not enough values to unpack (expected 2, got 1) again

I have this error and I am stuck here. Can someone help, please?

I am getting the error :

PS:- I am getting ([<'a': 'b'>], True) froma generator method.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You’re iterating over a tuple of two items:

In neither case do you have two items that can be unpacked into two variables.

What you seem to want to do is simply:

Not the answer you’re looking for? Browse other questions tagged python or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Распаковка в Python: За пределами параллельного назначения

Распаковка использует * для назначения нескольких переменных из одной итерации в одном операторе присваивания. Это делает ваш код Python чище и быстрее писать.

Вступление

В этом уроке мы узнаем, что такое итеративная распаковка и как мы можем воспользоваться этой функцией Python, чтобы сделать наш код более читабельным, ремонтопригодным и питоническим.

Кроме того, мы также рассмотрим некоторые практические примеры использования функции итеративной распаковки в контексте операций присваивания, для циклов, определений функций и вызовов функций.

Упаковка и распаковка в Python

Python позволяет кортежу (или списку ) переменных появляться в левой части операции присваивания. Каждая переменная в кортеже может получить одно значение (или несколько, если мы используем оператор * ) из итерации в правой части присваивания.

Операции распаковки были довольно популярны среди разработчиков Python, потому что они могут сделать наш код более читаемым и элегантным. Давайте подробнее рассмотрим распаковку в Python и посмотрим, как эта функция может улучшить наш код.

Распаковка кортежей

Поскольку все эти варианты являются допустимым синтаксисом Python, мы можем использовать любой из них, в зависимости от ситуации. Возможно, последний синтаксис чаще используется, когда дело доходит до распаковки в Python.

Примечание: Единственное исключение-это когда мы используем оператор * для упаковки нескольких значений в одну переменную, как мы увидим позже.

С другой стороны, если мы используем больше переменных, чем значений, то получим ValueError но на этот раз сообщение говорит о том, что недостаточно значений для распаковки:

Распаковка Итераций

Функция распаковки кортежей стала настолько популярной среди разработчиков Python, что синтаксис был расширен для работы с любым итеративным объектом. Единственное требование состоит в том, чтобы итерация давала ровно один элемент на переменную в принимающем кортеже (или списке ).

Ознакомьтесь со следующими примерами того, как итеративная распаковка работает в Python:

Когда дело доходит до распаковки в Python, мы можем использовать любую итерацию в правой части оператора присваивания. Левая сторона может быть заполнена кортежем или списком переменных. Посмотрите на следующий пример, в котором мы используем кортеж в правой части оператора присваивания:

Он работает точно так же, если мы используем итератор range() :

Несмотря на то, что это допустимый синтаксис Python, он обычно не используется в реальном коде и, возможно, немного сбивает с толку начинающих разработчиков Python.

Наконец, мы также можем использовать объекты set в операциях распаковки. Однако, поскольку наборы являются неупорядоченной коллекцией, порядок назначений может быть своего рода бессвязным и может привести к тонким ошибкам. Посмотрите на следующий пример:

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

Упаковка С Оператором *

Оператор * | известен в этом контексте как оператор распаковки кортежа (или итеративного)|/. Он расширяет функциональность распаковки, позволяя нам собирать или упаковывать несколько значений в одну переменную. В следующем примере мы упаковываем кортеж значений в одну переменную с помощью оператора * :

Упаковка конечных значений в b :

Упаковка исходных значений в a :

Упаковка одного значения в a потому что b и c являются обязательными:

Не указывая значения для обязательной переменной ( e ), возникает ошибка:

Обратите внимание, что мы не можем использовать оператор распаковки * для упаковки нескольких значений в одну переменную без добавления конечной запятой к переменной в левой части присваивания. Таким образом, следующий код не будет работать:

Использование упаковки и распаковки на практике

Операции упаковки и распаковки могут быть весьма полезны на практике. Они могут сделать ваш код понятным, читаемым и питоническим. Давайте рассмотрим некоторые распространенные случаи использования упаковки и распаковки в Python.

Назначение параллельно

Например, предположим, что у нас есть база данных о сотрудниках нашей компании, и нам нужно присвоить каждому элементу списка описательную переменную. Если мы проигнорируем, как итеративная распаковка работает в Python, мы можем заставить себя писать такой код:

Несмотря на то, что этот код работает, обработка индекса может быть неуклюжей, трудной для ввода и запутанной. Более чистое, более читаемое и питоническое решение может быть закодировано следующим образом:

Используя распаковку в Python, мы можем решить проблему предыдущего примера с помощью одного простого и элегантного утверждения. Это крошечное изменение сделало бы наш код более легким для чтения и понимания для начинающих разработчиков.

Обмен Значениями Между Переменными

Эта процедура состоит из трех шагов и новой временной переменной. Если мы используем распаковку в Python, то мы можем достичь того же результата за один и краткий шаг:

В операторе a,, a мы переназначаем a to b и b to a в одной строке кода. Это гораздо более читабельно и просто. Кроме того, обратите внимание, что при использовании этого метода нет необходимости в новой временной переменной.

Сбор Нескольких Значений С Помощью *

Когда мы работаем с некоторыми алгоритмами, могут возникнуть ситуации, в которых нам нужно разбить значения итерационной или последовательности на куски значений для дальнейшей обработки. В следующем примере показано, как использовать для этого операции list и slicing :

Несмотря на то, что этот код работает так, как мы ожидаем, работа с индексами и срезами может быть немного раздражающей, трудной для чтения и сбивающей с толку начинающих. У него также есть недостаток, заключающийся в том, что он делает код жестким и трудным в обслуживании. В этой ситуации итеративный оператор распаковки * и его способность упаковывать несколько значений в одну переменную могут быть отличным инструментом. Проверьте этот рефакторинг приведенного выше кода:

Если бы мы использовали последовательное срезание вместо итеративной распаковки в Python, то нам нужно было бы обновить наши индексы и срезы, чтобы правильно поймать новые значения.

Использование оператора * для упаковки нескольких значений в одну переменную может быть применено в различных конфигурациях при условии, что Python может однозначно определить, какой элемент (или элементы) назначить каждой переменной. Взгляните на следующие примеры:

Мы можем переместить оператор * в кортеж (или список ) переменных, чтобы собрать значения в соответствии с нашими потребностями. Единственное условие состоит в том, что Python может определить, какой переменной присвоить каждое значение.

Важно отметить, что мы не можем использовать более одного выражения stared в задании, если мы это сделаем, то получим SyntaxError следующим образом:

Удаление Ненужных Значений С Помощью *

Примечание: По умолчанию символ подчеркивания _ используется интерпретатором Python для хранения результирующего значения операторов, которые мы запускаем в интерактивном сеансе. Таким образом, в этом контексте использование этого символа для идентификации фиктивных переменных может быть неоднозначным.

Возврат кортежей в функциях

Функции Python могут возвращать несколько значений, разделенных запятыми. Поскольку мы можем определить объекты tuple без использования круглых скобок, этот вид операции можно интерпретировать как возврат tuple значений. Если мы закодируем функцию, которая возвращает несколько значений, то мы можем выполнять итеративные операции упаковки и распаковки с возвращаемыми значениями.

Рассмотрим следующий пример, в котором мы определяем функцию для вычисления квадрата и куба заданного числа:

Если мы определим функцию, которая возвращает значения, разделенные запятыми, то мы можем выполнить любую операцию упаковки или распаковки этих значений.

Слияние Итераций С Оператором *

Распаковка Словарей С Помощью Оператора **

Основным вариантом использования оператора распаковки словаря является объединение нескольких словарей в один окончательный словарь с одним выражением. Давайте посмотрим, как это работает:

Если мы используем оператор распаковки словаря внутри отображения словаря, то мы можем распаковать словари и объединить их, чтобы создать окончательный словарь, который включает пары ключ-значение исходных словарей, точно так же, как мы сделали это в приведенном выше коде.

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

Распаковка в For-Loops

В качестве примера предположим, что у нас есть файл, содержащий данные о продажах компании следующим образом:

0.25Карандаш1500
1.30Блокнот550
0.75Ластик1000

Из этой таблицы мы можем построить список кортежей из двух элементов. Каждый кортеж будет содержать название продукта, цену и проданные единицы. С помощью этой информации мы хотим рассчитать доход каждого продукта. Для этого мы можем использовать цикл for следующим образом:

Давайте рассмотрим альтернативную реализацию с использованием распаковки в Python:

Также можно использовать оператор * в цикле for для упаковки нескольких элементов в одну целевую переменную:

Наконец, структура целевых переменных должна согласовываться со структурой итерируемой. В противном случае мы получим ошибку. Взгляните на следующий пример:

Упаковка и распаковка в функциях

Мы также можем использовать функции упаковки и распаковки Python при определении и вызове функций. Это довольно полезный и популярный пример использования упаковки и распаковки в Python.

В этом разделе мы рассмотрим основы использования упаковки и распаковки в функциях Python либо в определении функции, либо в вызове функции.

Определение Функций С Помощью * и **

Мы можем использовать операторы * и ** в сигнатуре функций Python. Это позволит нам вызвать функцию с переменным числом позиционных аргументов ( * ) или с переменным числом аргументов ключевых слов, или и то, и другое. Рассмотрим следующую функцию:

Несмотря на то, что имена args и kwargs широко используются сообществом Python, они не являются обязательным требованием для работы этих методов. Синтаксис просто требует * или ** с последующим допустимым идентификатором. Итак, если вы можете дать значимые имена этим аргументам, то сделайте это. Это, безусловно, улучшит читабельность вашего кода.

Вызов Функций С Помощью * и **

При вызове функций мы также можем извлечь выгоду из использования операторов * и ** для распаковки коллекций аргументов в отдельные позиционные или ключевые аргументы соответственно. Это обратная ситуация использования * и ** в сигнатуре функции. В сигнатуре операторы означают collect или pack переменное число аргументов в одном идентификаторе. В вызове они означают распаковать итерацию на несколько аргументов.

Вот основной пример того, как это работает:

Здесь оператор * распаковывает последовательности типа [«Welcome», «to»] в позиционные аргументы. Аналогично оператор ** распаковывает словари в аргументы, имена которых совпадают с ключами распакованного словаря.

Мы также можем объединить эту технику и ту, которая описана в предыдущем разделе, чтобы написать достаточно гибкие функции. Вот пример:

Использование операторов * и ** при определении и вызове функций Python даст им дополнительные возможности и сделает их более гибкими и мощными.

Вывод

В этом уроке мы узнали, как использовать итеративную распаковку в Python для написания более читаемого, поддерживаемого и питонического кода.

Обладая этими знаниями, мы теперь можем использовать итеративную распаковку в Python для решения общих проблем, таких как параллельное присвоение и обмен значениями между переменными. Мы также можем использовать эту функцию Python в других структурах, таких как for циклы, вызовы функций и определения функций.

ValueError: not enough values to unpack (expected 3, got 2)

first time posting a question so go easy on me.

I found some code online that i am trying to implement myself though i keep coming across this error

ValueError: not enough values to unpack (expected 3, got 2)

the code is as follows:

If you can help me out this would be great 🙂

3 Answers 3

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

To add to timgeb’s answer, the solution is to change the header of your for loop:

which is the same as:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

enumerate gives your an iterator over (index, value) tuples which are always of length two.

Not enough values to unpack(expected 2, got 1) using odeint [closed]

I have been trying to numerically solve the Rayleigh Plesset equation. I have written

However, when I run the code I found the following error: ValueError: not enough values to unpack (expected 2, got 1).

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

In this line of code;

You are attempting to set 2 variables in one line, however only providing one value.

You need to set 2 values or only assign one variable here.

R, u = y0, 1 as an example.

Ok. So I have passed in two variables to the equation, and the code looks like this:

»’ import numpy as np from matplotlib import pyplot as plt from scipy.integrate import odeint

However, when i run the code I get a a useless graph which doesn’t make any sense at all. I’ve used the parameters as defined here: https://people.eng.unimelb.edu.au/asho/AdvCompMech/Assignment_1.pdf

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python or ask your own question.

Related

Hot Network Questions

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

I am trying to convert a float to its binary representation. I don’t get why when I try to split the whole number and the decimal part, I get this error

ValueError: not enough values to unpack (expected 2, got 1)

Here is the code

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

your problem is with the representation of your number in form 5.67e-05. When you convert this to string your code breaks

Instead you can use the following function

and the output will be

For correct function output, you might need this

from ctypes import *

You defined «dec» as an integer in line 6, then you perform integer (floor) division on it in decimal_converter, which also returns an integer, which then has no decimal point to split on.

Not the answer you’re looking for? Browse other questions tagged python python-3.x or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Getting the mentioned error when trying to execute this excel comparison script, please help. Objective of the script is to be able to compare both the excel and highlight the difference, also would be great if you can suggest how can I include columns like Primary Key

1 Answer 1

In your example, it seems like df1 and df2 are both one-dimensional arrays. Hence, the numpy’s where() function returns a tuple containing one single value, so when you type:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python pandas or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

ValueError: not enough values to unpack (expected 2, got 1) NetworkX python 3

The error reported

where, len(edge_labels) = 150

When i pass the edge labels dictionary inside nx.draw_networkx_edge_labels using «labels» argument instead of «edge_labels», it shows empty dictionaries as shown in picture. But i am looking for edge labels with key:value entries. Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

1 Answer 1

The documentation for draw_networkx_edge_labels states that the edge_labels argument requires a dictionary where the keys are tuples with two elements:

edge_labels (dictionary) – Edge labels in a dictionary keyed by edge two-tuple of text labels (default=None). Only labels for the keys in the dictionary are drawn.

Your keys are single strings.

The tuples represent edges; in your graph those are tuples of integers, listed in map_paths_reduced ; your label keys must match those edges.

Python3 make file into dictionary ValueError: not enough values to unpack (expected 2, got 1)

My problem is how to convert text files into dictionaries This is my code. And i got error ValueError: not enough values to unpack (expected 2, got 1)

pardon my english.Thanks

1 Answer 1

You were getting error because there were no space in first data line and data should be split by / not space. to get the expected output you can use below sample code.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python-3.x file dictionary or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

not enough values to unpack (expected 2, got 1) when I use argparse

Im trying to pass a dict (as a string) as an argument to a python script. when i run it from terminal I get an error

From terminal this I run :

Could someone be able to help me fix this error. Below is the python script

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

This part is where I think the problem is:

The problem is in the ‘for’ statement json.loads returns a dict and it is this that is the one thing that is unpacked. you need to change the ‘for’ statement to read:

You can also use the module ast and its function literal_eval() to convert to a dict, then use items() method to iterate over (key, value) pairs. Like so:

Django python ValueError: not enough values to unpack (expected 2, got 1)

I have this code to in my views.py that will export to excel, i combined two query in 1 loop but i receive this error Exception Type: ValueError at /export_reportF/ Exception Value: not enough values to unpack (expected 2, got 1)

this is the traceback Exception Type: ValueError at /export_reportF/ Exception Value: not enough values to unpack (expected 2, got 1)

1 Answer 1

What this gives you is a list which contains two lists. If you loop over it, it will loop twice, first giving you the reports list and then the daily list. Try this:

That should make the problem obvious. The solution is to replace line 3 with this:

Which will give you an iterable of pairs, where each pair has one report and one day in it.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Getting common characters of two strings results in «ValueError: not enough values to unpack»

I have created 2 strings and I am trying to iterate through each character in the string by storing them in those 2 variables a and b and then replacing them with the next character as the loop continues. Finally, I have added the if-condition that at any point in the iteration if the values in a and b match then first print the common characters.

Both the print commands must display «ho» as the output, however, I am getting the error not enough values to unpack (expected 2, got 1) instead.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Well, there are some problems to solve:

So, the code you want may be:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Use zip. This will handle the case where the strings are of different lengths

Getting the mentioned error when trying to execute this excel comparison script, please help. Objective of the script is to be able to compare both the excel and highlight the difference, also would be great if you can suggest how can I include columns like Primary Key

1 Answer 1

In your example, it seems like df1 and df2 are both one-dimensional arrays. Hence, the numpy’s where() function returns a tuple containing one single value, so when you type:

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Not the answer you’re looking for? Browse other questions tagged python pandas or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Meshgrid, not enough values to unpack (expected 2,got 1)

maybe it will be a very basic question for the experts but I am just a beginner. I have multiple time series signals from different distances. I plotted all time series data with the help of the plt.plot command as given in the below script.

Here is my tried, even if it is not so good as a beginner of Python. Or is there any other suggested way to do this?

1 Answer 1

Do not worry about being a beginner, good that you ask questions. It will help others in similar situation as you.

I can reproduce your error with a modified example from the matplotlib docs gallery (here https://matplotlib.org/stable/gallery/images_contours_and_fields/pcolormesh_levels.html). If I run

I get ValueError: not enough values to unpack (expected 2, got 1) For it to work I need to change the last line to ax.pcolormesh(x, y, Z)

So the problem is most likely that your zarray is not the right shape. I believe it needs to be a (Ny, Nx) sized matrix, where Ny is the length of the yarray, and Nx the length of the xarray. Perhaps run the example, and check the shape and size of the x,y, Z array and compare to yours.

(If you did not mess with rcParams, your shading parameter of pcolormesh should be set to ‘auto’ and should not matter if you give the quadrilateral, square in your case, edges or the center coordinates for x and y)

Python ValueError: not enough values to unpack Solution

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Unpacking syntax lets you separate the values from iterable objects. If you try to unpack more values than the total that exist in an iterable object, you’ll encounter the “ValueError: not enough values to unpack” error.

This guide discusses what this error means and why you may see it in your code. We’ll walk through an example of this error in action so you can see how it works.

Valueerror not enough values to unpack expected 2 got 1. Смотреть фото Valueerror not enough values to unpack expected 2 got 1. Смотреть картинку Valueerror not enough values to unpack expected 2 got 1. Картинка про Valueerror not enough values to unpack expected 2 got 1. Фото Valueerror not enough values to unpack expected 2 got 1

Find Your Bootcamp Match

Select your interest
First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

ValueError: not enough values to unpack

Iterable objects like lists can be “unpacked”. This lets you assign the values from an iterable object into multiple variables.

Unpacking is common when you want to retrieve multiple values from the response of a function call, when you want to split a list into two or more variables depending on the position of the items in the list, or when you want to iterate over a dictionary using the items() method.

Consider the following example:

This code unpacks the values from our list into two variables: name and address. The variable “name” will be given the value “John Doe” and the variable address will be assigned the value “123 Main Street”.

You have to unpack every item in an iterable if you use unpacking. You cannot unpack fewer or more values than exist in an iterable. This is because Python would not know which values should be assigned to which variables.

An Example Scenario

We’re going to write a program that calculates the total sales of a product at a cheese store on a given day. To start, we’re going to ask the user to insert two pieces of information: the name of a cheese and a list of all the sales that have been made.

We can do this using an input() statement:

Our “sales” variable expects the user to insert a list of sales. Each value should be separated using a comma.

The split() method turns the values the user gives us into a list. We use a list comprehension to turn each value from our string into a float and put that number in a list.

We use the sum() method to calculate the total value of all the purchases for a given cheese based on the list that the split() method returns. We then use an if statement to determine whether a cheese is a top seller.

Our method returns an iterable with one item: the total sales made. We return an iterable so we can unpack it later in our program. Next, call our function:

Our function accepts one parameter: the list of purchases. We unpack the result of our function into two parts: total_sales and top_seller.

Finally, print out the values that our function calculates:

We convert our variables to strings so we can concatenate them to our labels. We round the value of “total_sales” to two decimal places using the round() method. Let’s run our program and see if it works:

Our program fails to execute.

The Solution

The calculate_total_sales() function only returns one value: the total value of all the sales made of a particular cheese. However, we are trying to unpack two values from that function.

This causes an error because Python is expecting a second value to unpack. To solve this error, we have to return the “top_seller” value into our main program:

Our function now returns a list with two values: total_sales and top_seller. These two values can be unpacked by our program because they appear in a list. Let’s run our program and see if it works:

Our program now successfully displays the total sales of a cheese and whether that cheese is a top seller to the console.

Conclusion

The “ValueError: not enough values to unpack” error is raised when you try to unpack more values from an iterable object than those that exist. To fix this error, make sure the number of values you unpack from an iterable is equal to the number of values in that iterable.

Now you have the knowledge you need to fix this common Python error like an expert!

Python Error: Too Many Values To Unpack. Let’s Fix It!

The error “too many values to unpack” is common in Python, you might have seen it while working with lists.

The Python error “too many values to unpack” occurs when you try to extract a number of values from a data structure into variables that don’t match the number of values. For example, if you try to unpack the elements of a list into variables whose number doesn’t match the number of elements in the list.

We will look together at some scenarios in which this error occurs, for example when unpacking lists, dictionaries or when calling Python functions.

By the end of this tutorial you will know how to fix this error if you happen to see it.

Let’s get started!

Table of Contents

How Do You Fix the Too Many Values to Unpack Error in Python

What causes the too many values to unpack error?

This happens, for example, when you try to unpack values from a list.

Let’s see a simple example:

The error complains about the fact that the values on the right side of the expression are too many to be assigned to the variables day1, day2 and day3.

As you can see from the traceback this is an error of type ValueError.

So, what can we do?

One option could be to use a number of variables on the left that matches the number of values to unpack, in this case seven:

This time there’s no error and each variable has one of the values inside the week_days array.

In this example the error was raised because we had too many values to assign to the variables in our expression.

Let’s see what happens if we don’t have enough values to assign to variables:

This time we only have two values and we are trying to assign them to the three variables day1, day2 and day3.

That’s why the error says that it’s expecting 3 values but it only got 2.

In this case the correct expression would be:

Another Error When Calling a Python Function

The same error can occur when you call a Python function incorrectly.

I will define a simple function that takes a number as input, x, and returns as output two numbers, the square and the cube of x.

What happens if, by mistake, I assign the values returned by the function to three variables instead of two?

We see the error “not enough values to unpack” because the value to unpack are two but the variables on the left side of the expression are three.

And what if I assign the output of the function to a single variable?

Everything works well and Python makes the ouput variable a tuple that contains both values returned by the getSquareAndCube function.

Too Many Values to Unpack With the Input Function

Another common scenario in which this error can occur is when you use the Python input() function to ask users to provide inputs.

The Python input() function reads the input from the user and it converts it into a string before returning it.

Here’s a simple example:

Wait a minute, what’s happening here?

Why Python is complaining about too many values to unpack?

That’s because the input() function converts the input into a string, in this case “Claudio Sabato”, and then it tries to assign each character of the string to the variables on the left.

So we have multiple characters on the right part of the expression being assigned to two variables, that’s why Python is saying that it expects two values.

What can we do about it?

We can apply the string method split() to the ouput of the input function:

The split method converts the string returned by the input function into a list of strings and the two elements of the list get assigned to the variables name and surname.

By default, the split method uses the space as separator. If you want to use a different separator you can pass it as first parameter to the split method.

Using Maxsplit to Solve This Python Error

There is also another way to solve the problem we have observed while unpacking the values of a list.

Let’s start again from the following code:

This time I will provide a different string to the input function:

In a similar way as we have seen before, this error occurs because split converts the input string into a list of three elements. And three elements cannot be assigned to two variables.

There’s a way to tell Python to split the string returned by the input function into a number of values that matches the number of variables, in this case two.

Here is the generic syntax for the split method that allows to do that:

The maxsplit parameter defines the maximum number of splits to be used by the Python split method when converting a string into a list. Maxsplit is an optional parameter.

So, in our case, let’s see what happens if we set maxsplit to 1.

The error is gone, the logic of this line is not perfect considering that surname is ‘John Smith’. But this is just an example to show how maxsplit works.

So, why are we setting maxsplit to 1?

Because in this way the string returned by the input function is only split once when being converted into a list, this means the result is a list with two elements (matching the two variables on the left of our expression).

Too Many Values to Unpack with Python Dictionary

In the last example we will use a Python dictionary to explain another common error that shows up while developing.

I have created a simple program to print every key and value in the users dictionary:

When I run it I see the following error:

Where is the problem?

Let’s try to execute a for loop using just one variable:

When we loop through a dictionary using its name we get back just the keys.

That’s why we were seeing an error before, we were trying to unpack each key into two variables: key and value.

To retrieve each key and value from a dictionary we need to use the dictionary items() method.

Let’s run the following:

This time the output is:

At every iteration of the for loop we get back a tuple that contains a key and its value. This is definitely something we can assign to the two variables we were using before.

So, our program becomes:

The program prints the following output:

All good, the error is fixed!

Conclusion

We have seen few examples that show when the error “too many values to unpack” occurs and how to fix this Python error.

In one of the examples we have also seen the error “not enough values to unpack”.

Both errors are caused by the fact that we are trying to assign a number of values that don’t match the number of variables we assign them to.

And you? Where are you seeing this error?

Let me know in the comments below 🙂

I have also created a Python program that will help you go through the steps in this tutorial. You can download the source code here.

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Распаковка в Python: помимо параллельного присвоения

Введение Распаковка в Python относится к операции, которая состоит из присвоения итерации значений кортежу [/ lists-vs-tuples-in-python /] (или списку) переменных в одном операторе присваивания. В качестве дополнения можно использовать термин упаковка, когда мы собираем несколько значений в одной переменной с помощью итеративного оператора распаковки *. Исторически сложилось так, что разработчики Python обычно называли этот вид операции распаковкой кортежа. Однако, поскольку эта функция Python оказалась

Время чтения: 20 мин.

Вступление

В этом руководстве мы узнаем, что такое итеративная распаковка и как мы можем воспользоваться этой функцией Python, чтобы сделать наш код более читабельным, поддерживаемым и питоническим.

Кроме того, мы также рассмотрим несколько практических примеров того, как использовать функцию повторяющейся распаковки в контексте операций присваивания, for циклов, определений функций и вызовов функций.

Упаковка и распаковка в Python

Python позволяет tuple (или list ) переменных слева от операции присваивания. Каждая переменная в tuple может получать одно значение (или несколько, если мы используем * ) из итерации в правой части присваивания.

Операции распаковки были довольно популярны среди разработчиков Python, потому что они могут сделать наш код более читаемым и элегантным. Давайте подробнее рассмотрим распаковку в Python и посмотрим, как эта функция может улучшить наш код.

Распаковка кортежей

Поскольку все эти варианты являются допустимым синтаксисом Python, мы можем использовать любой из них, в зависимости от ситуации. Возможно, последний синтаксис чаще используется, когда дело доходит до распаковки в Python.

Например, в следующем коде мы используем две переменные слева и три значения справа. Это вызовет ValueError сообщающую нам, что слишком много значений для распаковки:

С другой стороны, если мы используем больше переменных, чем значений, мы получим ValueError но на этот раз сообщение говорит, что недостаточно значений для распаковки:

Распаковка итераций

Функция распаковки кортежей стала настолько популярной среди разработчиков Python, что синтаксис был расширен для работы с любым итеративным объектом. Единственное требование состоит в том, чтобы итерация давала ровно один элемент для каждой переменной в принимающем tuple (или list ).

Ознакомьтесь со следующими примерами того, как итеративная распаковка работает в Python:

Когда дело доходит до распаковки в Python, мы можем использовать любую итерацию справа от оператора присваивания. Левая часть может быть заполнена tuple или list переменных. Посмотрите следующий пример, в котором мы используем tuple в правой части оператора присваивания:

Это работает точно так же, если мы используем итератор range()

Несмотря на то, что это допустимый синтаксис Python, он обычно не используется в реальном коде и может немного сбивать с толку начинающих разработчиков Python.

Наконец, мы также можем использовать set объекты в операциях распаковки. Однако, поскольку наборы представляют собой неупорядоченную коллекцию, порядок назначений может быть в некотором роде непоследовательным и может привести к незаметным ошибкам. Посмотрите следующий пример:

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

Упаковка с оператором *

Мы можем сформировать начальное выражение, используя оператор распаковки * вместе с действительным идентификатором Python, как *a в приведенном выше коде. Остальные переменные в левом tuple называются обязательными переменными, потому что они должны быть заполнены конкретными значениями, иначе мы получим ошибку. Вот как это работает на практике.

Упаковка конечных значений в b :

Упаковка начальных значений в : a

Упаковка одного значения в a потому что b и c являются обязательными:

Отсутствует значение обязательной переменной ( e ), поэтому возникает ошибка:

Использование упаковки и распаковки на практике

Операции по упаковке и распаковке могут оказаться весьма полезными на практике. Они могут сделать ваш код понятным, читаемым и питоническим. Давайте рассмотрим некоторые распространенные варианты использования упаковки и распаковки в Python.

Назначение параллельно

Например, предположим, что у нас есть база данных о сотрудниках в нашей компании, и нам нужно назначить каждый элемент в списке описательной переменной. Если мы проигнорируем, как итеративная распаковка работает в Python, мы можем написать такой код:

Несмотря на то, что этот код работает, обработка индекса может быть неуклюжей, сложной для ввода и запутанной. Более чистое, более читаемое и питоническое решение можно закодировать следующим образом:

Используя распаковку в Python, мы можем решить проблему из предыдущего примера с помощью одного простого и элегантного оператора. Это крошечное изменение сделало бы наш код более легким для чтения и понимания для начинающих разработчиков.

Обмен значениями между переменными

Эта процедура состоит из трех шагов и новой временной переменной. Если мы используем распаковку в Python, то мы можем добиться того же результата за один краткий шаг:

В заявлении a, b = b, a мы переназначаем a на b и b на a в одной строке кода. Это намного удобнее и понятнее. Также обратите внимание, что при использовании этого метода нет необходимости в новой временной переменной.

Сбор нескольких значений с помощью *

Когда мы работаем с некоторыми алгоритмами, могут возникать ситуации, в которых нам нужно разделить значения итерации или последовательности на порции значений для дальнейшей обработки. В следующем примере показано, как для этого использовать list и операции нарезки :

Несмотря на то, что этот код работает так, как мы ожидаем, работа с индексами и срезами может быть немного раздражающей, сложной для чтения и запутанной для новичков. У него также есть недостаток, заключающийся в том, что код становится жестким и трудным в поддержке. В этой ситуации итеративный оператор распаковки * и его способность упаковывать несколько значений в одну переменную могут быть отличным инструментом. Посмотрите этот рефакторинг приведенного выше кода:

Если бы мы использовали нарезку последовательности вместо итеративной распаковки в Python, тогда нам нужно было бы обновить наши индексы и фрагменты, чтобы правильно улавливать новые значения.

Использование * для упаковки нескольких значений в одну переменную может применяться в различных конфигурациях при условии, что Python может однозначно определять, какой элемент (или элементы) назначить каждой переменной. Взгляните на следующие примеры:

Важно отметить, что мы не можем использовать более одного начального выражения в присваивании. Если мы это сделаем, то получим SyntaxError следующим образом:

Если мы используем два или более * в выражении присваивания, то мы получим SyntaxError сообщающее нам, что найдено выражение, помеченное двумя звездами. Это так, потому что Python не может однозначно определить, какое значение (или значения) мы хотим присвоить каждой переменной.

Удаление ненужных значений с помощью *

Примечание. По умолчанию символ подчеркивания _ используется интерпретатором Python для хранения результирующего значения операторов, которые мы запускаем в интерактивном сеансе. Таким образом, в этом контексте использование этого символа для идентификации фиктивных переменных может быть неоднозначным.

Возврат кортежей в функциях

Функции Python могут возвращать несколько значений, разделенных запятыми. Поскольку мы можем определять tuple без использования круглых скобок, этот вид операции можно интерпретировать как возврат tuple значений. Если мы кодируем функцию, которая возвращает несколько значений, мы можем выполнять итерационные операции упаковки и распаковки с возвращенными значениями.

Посмотрите следующий пример, в котором мы определяем функцию для вычисления квадрата и куба заданного числа:

Если мы определим функцию, которая возвращает значения, разделенные запятыми, то мы можем выполнить любую операцию упаковки или распаковки этих значений.

Слияние итераций с оператором *

Распаковка словарей с помощью ** Оператора

Если мы используем оператор распаковки словаря внутри отображения словаря, мы можем распаковать словари и объединить их для создания окончательного словаря, который включает пары ключ-значение исходных словарей, как мы это сделали в приведенном выше коде.

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

Распаковка в For-Loops

В качестве примера предположим, что у нас есть файл, содержащий следующие данные о продажах компании:

Продукт Цена Проданные единицы

Из этой таблицы мы можем построить list двухэлементных кортежей. Каждый tuple будет содержать название продукта, цену и проданные единицы. Имея эту информацию, мы хотим рассчитать доход от каждого продукта. Для этого мы можем использовать такой цикл for

Давайте посмотрим на альтернативную реализацию с использованием распаковки в Python:

Также можно использовать оператор * for чтобы упаковать несколько элементов в одну целевую переменную:

Наконец, структура целевых переменных должна соответствовать структуре итерируемого. В противном случае мы получим ошибку. Взгляните на следующий пример:

Упаковка и распаковка в функциях

Мы также можем использовать функции упаковки и распаковки Python при определении и вызове функций. Это довольно полезный и популярный вариант упаковки и распаковки в Python.

В этом разделе мы рассмотрим основы использования упаковки и распаковки в функциях Python либо в определении функции, либо в ее вызове.

Определение функций с помощью * и **

Мы можем использовать * и ** в сигнатуре функций Python. Это позволит нам вызывать функцию с переменным количеством позиционных аргументов ( * ) или с переменным количеством аргументов ключевого слова, или с обоими. Рассмотрим следующую функцию:

Несмотря на то, что имена args и kwargs широко используются сообществом Python, они не являются обязательными для работы этих методов. Синтаксис просто требует * или ** за которым следует действительный идентификатор. Итак, если вы можете дать этим аргументам осмысленные имена, то сделайте это. Это, безусловно, улучшит читаемость вашего кода.

Вызов функций с помощью * и **

При вызове функций мы также можем извлечь выгоду из использования * и ** для распаковки наборов аргументов в отдельные позиционные или ключевые аргументы соответственно. Это противоположно использованию * и ** в сигнатуре функции. В подписи операторы означают сбор или упаковку переменного количества аргументов в один идентификатор. В вызове они означают распаковку итерации на несколько аргументов.

Вот простой пример того, как это работает:

Здесь * распаковывает последовательности вроде [«Welcome», «to»] в позиционные аргументы. Аналогичным образом ** распаковывает словари в аргументы, имена которых соответствуют ключам распакованного словаря.

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

Использование * и ** при определении и вызове функций Python предоставит им дополнительные возможности и сделает их более гибкими и мощными.

Заключение

В этом руководстве мы узнали, как использовать итеративную распаковку в Python для написания более читаемого, поддерживаемого и питонического кода.

ValueError: not enough values to unpack (expected 2, got 1) #372

Comments

yasminaaq commented Mar 18, 2021

I keep getting this error when calling detect_language.
This has started happening today only.

The text was updated successfully, but these errors were encountered:

igalma commented Mar 18, 2021 •

calling translate also results in in exception because in _validate_translation function result.strip() is trying to strip a list.
For some reason the returned value from the api changed to a very nested list.

quillfires commented Mar 18, 2021

I keep getting the same error when calling detect_language. Perhaps they changed changed their translate API again. Need a fix 😩

bappctl commented Mar 18, 2021 •

Running into same issue starting today. Surprisingly this library was pip installed a month back and working. Does this library get auto updated (which is not supposed to happen)

mishra011 commented Mar 19, 2021

same issue

File «/home/deepak/miniconda3/lib/python3.8/site-packages/textblob/blob.py», line 568, in detect_language
return self.translator.detect(self.raw)
File «/home/deepak/miniconda3/lib/python3.8/site-packages/textblob/translate.py», line 73, in detect
result, language = json.loads(response)
ValueError: not enough values to unpack (expected 2, got 1)

quillfires commented Mar 19, 2021 •

Running into same issue starting today. Surprisingly this library was pip installed a month back and working. Does this library get auto updated (which is not supposed to happen)

Its not related to an update afaik.. And no update was released to pypi as well. It uses Google’s translation API to do the thing. Most probably they’ve changed something up causing this to fall. We really need a good fix fast cause there’s nothing better than this for this task

igalma commented Mar 19, 2021 •

In the mean time I took the relevant functions and did some modifications to make it work. You guys can just copy this code and it will work (just fix some minor issues that created while copy pasting my code):

from textblob.exceptions import NotTranslated
import ctypes
import json
from textblob.compat import request, urlencode

headers = <
‘Accept’: ‘/’,
‘Connection’: ‘keep-alive’,
‘User-Agent’: (
‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) ‘
‘AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19’)
>

language = detect(source=»some text in any language»)

def detect(source, host=None, type_=None):
«»»Detect the source text’s language.»»»
if len(source) > d if b[c + 1] == ‘+’ else xa = 0 else ((a & 2147483647) + 2147483648) a %= pow(10, 6) tk = ‘<0:d>.<1:d>‘.format(a, a ^ b) return tk»>

quillfires commented Mar 19, 2021

this worked. why dont you pr and do this??

igalma commented Mar 19, 2021

Because I’m not a contributor. Just solved it for myself and decided to share.

quillfires commented Mar 22, 2021

In the mean time I took the relevant functions and did some modifications to make it work. You guys can just copy this code and it will work (just fix some minor issues that created while copy pasting my code):

from textblob.exceptions import NotTranslated
import ctypes
import json
from textblob.compat import request, urlencode

headers = <
‘Accept’: ‘/’,
‘Connection’: ‘keep-alive’,
‘User-Agent’: (
‘Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) ‘
‘AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19’)
>

language = detect(source=»some text in any language»)

def detect(source, host=None, type_=None):
«»»Detect the source text’s language.»»»
if len(source) > d if b[c + 1] == ‘+’ else xa = 0 else ((a & 2147483647) + 2147483648) a %= pow(10, 6) tk = ‘<0:d>.<1:d>‘.format(a, a ^ b) return tk»>

Is this still working for you? 🤔

igalma commented Mar 23, 2021

Seems they changed the api back to what it used to be so you can move back to the original way you used it

bappctl commented Mar 23, 2021

Seems they changed the api back to what it used to be so you can move back to the original way you used it

markfilan commented Apr 18, 2022

During a multiple value assignment, the ValueError: not enough values to unpack occurs when either you have fewer objects to assign than variables, or you have more variables than objects. This error caused by the mismatch between the number of values returned and the number of variables in the assignment statement. This error happened mostly in the case of using python split function. Verify the assignment variables. If the number of assignment variables is greater than the total number of variables, delete the excess variable from the assignment operator. The number of objects returned, as well as the number of variables available are the same.

To see what line is causing the issue, you could add some debug statements like this:

ValueError: not enough values to unpack (expected 2, got 1) #87

Comments

folkaholic commented Mar 3, 2020 •

I got this error:
Traceback (most recent call last):
File «main.py», line 135, in
main()
File «main.py», line 132, in main
test(cfg, args)
File «main.py», line 81, in test
model.test(visualize=args.visualize)
File «../graph-rcnn.pytorch/lib/model.py», line 234, in test
output, output_pred = output
ValueError: not enough values to unpack (expected 2, got 1)

I don’t know why 🙁
Anyone help? Thanks

The text was updated successfully, but these errors were encountered:

nyj-ocean commented Jun 17, 2020

@folkaholic
I meet the same issue with you
have you solved this issue?
how to solved it?

wffancy commented Nov 2, 2020 •

When I removed the last argument, namely the algothrim, I can get rid of such error. However, the visualized results seem to be only belong to the detector without any image indicating the relationship between objects. How’s it going? Need Help here, thanks

ValueError: not enough values to unpack (expected 2, got 1) #1119

Comments

sadaction commented Jan 20, 2020 •

Здравствуйте!
пробую обучить модель по вашим инструкциям описанным в #890
получаю ошибку ValueError: not enough values to unpack (expected 2, got 1)

проверил и вычистил перенос строки в середине text в train.csv
train.csv имеет вид:
text,classes,classes_1,classes_2
«Периодически выпадает табло ‘Неисправность СГИУ’. Сообщение в журнале 1ШСКД ‘нет связи с ШСКД по каналу 100 BASE 2FX’.»,0,3,249
«Не создает давление лубрикатор компрессора №2.»,0,2,211
«Нет переводится с ‘автомата’ на ручное управление привод.»,0,2,217

classes.dict имеет следующий вид
classes 0
classes_1 3
classes_2 249
Name: 9622, dtype: object 1
classes 0
classes_1 2
classes_2 173
Name: 5283, dtype: object 1
classes 0
classes_1 2
classes_2 166
Name: 7745, dtype: object 1
classes 1
classes_1 2
classes_2 33
Name: 14129, dtype: object 1

между classes и значением стоят пробелы, хотя как я понял из кода разделителем должен быть знак табуляции.

файл конфига
<
«dataset_reader»: <
«class_name»: «basic_classification_reader»,
«x»: «text»,
«y»: [«classes»,»classes_1″,»classes_2″],
«data_path»: «/var/local/»,
«train»: «train_main.csv»,
«test»: «train_test.csv»
>,
«dataset_iterator»: <
«class_name»: «basic_classification_iterator»,
«seed»: 42,
«split_seed»: 23,
«field_to_split»: «train»,
«split_fields»: [
«train»,
«valid»
],
«split_proportions»: [
0.9,
0.1
]
>,
«chainer»: <
«in»: [
«x»
],
«in_y»: [
«y»
],
«pipe»: [
<
«class_name»: «bert_preprocessor»,
«n_classes»:3,
«vocab_file»: «/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v1/vocab.txt»,
«do_lower_case»: false,
«max_seq_length»: 64,
«in»: [
«x»
],
«out»: [
«bert_features»
]
>,
<
«id»: «classes_vocab»,
«class_name»: «simple_vocab»,
«fit_on»: [
«y»
],
«save_path»: «/var/local/classes.dict»,
«load_path»: «/var/local/classes.dict»,
«in»: «y»,
«out»: «y_ids»
>,
<
«in»: «y_ids»,
«out»: «y_onehot»,
«class_name»: «one_hotter»,
«depth»: «#classes_vocab.len»,
«single_vector»: true
>,
<
«class_name»: «bert_classifier»,
«n_classes»: 3,
«return_probas»: true,
«one_hot_labels»: true,
«bert_config_file»: «/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v1/bert_config.json»,
«pretrained_bert»: «/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v1/bert_model.ckpt»,
«save_path»: «/var/local/models/model»,
«load_path»: «/var/local/models/model»,
«keep_prob»: 0.5,
«optimizer»: «tf.train:AdamOptimizer»,
«learning_rate»: 1e-05,
«learning_rate_drop_patience»: 3,
«learning_rate_drop_div»: 2.0,
«in»: [
«bert_features»
],
«in_y»: [
«y_onehot»
],
«out»: [
«y_pred_probas»
]
>,
<
«in»: «y_pred_probas»,
«out»: «y_pred_ids»,
«class_name»: «proba2labels»,
«max_proba»: true
>,
<
«in»: «y_pred_ids»,
«out»: «y_pred_labels»,
«ref»: «classes_vocab»
>
],
«out»: [
«y_pred_labels»
]
>,
«train»: <
«batch_size»: 4,
«epochs»: 40,
«metrics»: [
«sets_accuracy»
],
«validation_patience»: 3,
«val_every_n_epochs»: 1,
«log_every_n_epochs»: 1,
«show_examples»: false,
«evaluation_targets»: [
«train»,
«valid»,
«test»
],
«class_name»: «nn_trainer»,
«tensorboard_log_dir»: «/var/local/models/»
>,
«metadata»: <
«requirements»: [
«/requirements/tf.txt»,
«/requirements/bert_dp.txt»
]
>
>

The text was updated successfully, but these errors were encountered:

Источники:

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

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