- Блог
- Почему я не могу изменить значение списка с помощью лямбда-выражения в Python?
- Вопрос:
- Комментарии:
- Ответ №1:
- Комментарии:
- Ответ №2:
- Understanding and Avoiding Syntax Errors in Python Dictionaries
- Causes of Syntax Errors in Python Dictionaries
- Differentiating between ‘=’ and ‘==’ in context of Python Dictionaries
- Syntax Rules for Python Dictionaries
- Reproducing the Syntax Error: expression cannot contain assignment, perhaps you meant “==”?
- Mitigating Syntax Errors in Python Dictionaries
- Key Takeaways: Avoiding Syntax Errors in Python Dictionaries
- Running GRASS r.watershed in Python returns SyntaxError: expression cannot contain assignment
- 1 Answer 1
- Python Dictionary Object: SyntaxError: expression cannot contain assignment, perhaps you meant “==”
- Best Solution
Блог
Главная — Вопросы по программированию — Почему я не могу изменить значение списка с помощью лямбда-выражения в Python?
Почему я не могу изменить значение списка с помощью лямбда-выражения в Python?
#python #list #lambda
#python #Список #лямбда
Вопрос:
goods = [True, False, True, True, False, True, False]
Мне нужно инвертировать некоторые значения по индексам, например: 1, 3, 4
Это означает, что goods[1] будет True, goods [3] — False, goods [4] — True .
Если я делаю это в map lambda, я улавливаю ошибку, подобную этой:
SyntaxError: expression cannot contain assignment, perhaps you meant "= hljs-built_in">list(map(lambda x: goods[x]=True if goods[x] is False else True, [1, 3, 4]))
Почему я не могу изменить значение списка в таком случае?
Комментарии:
1. Условное выражение (X, если Y, иначе Z) требует выражений для каждого компонента. goods[x]=True это не выражение; это оператор присваивания. Если вы пытаетесь изменить содержимое goods in place , помещение присваивания внутрь map не является жизнеспособным способом сделать это.
2. Вы могли бы просто написать прямой цикл for.
Ответ №1:
Не пытайтесь злоупотреблять пониманием (или коллекциями) из-за побочных эффектов. Почему бы просто не:
for x in [1, 3, 4]: goods[x] = not goods[x]
Если бы из-за какого-то ошибочного эстетического чувства кто-то отчаянно хотел использовать лямбда-функцию, вам пришлось бы использовать ее для перестройки самих goods себя (лямбды могут содержать только одно выражение, а не оператор, где присваивание является оператором):
goods[:] = map(lambda x: not x[1] if x[0] in [1, 3, 4] else x[1], enumerate(goods))
Хотя в этом нет ничего изящного =)
Комментарии:
1. Это более простой и правильный способ сделать это. 1
2. И если это должно быть однострочное, просто сделайте for x in [1, 3, 4]: goods[x] = not goods[x] xD
3. Согласитесь, это более простой и легкий способ сделать это. Но есть ли способ сделать это с помощью лямбды и т.д.? Я хотел бы сделать это более изящно, если это возможно. Как вы думаете? Строка, подобная этой для x в [1, 3, 4]: товары [x] = не товары [x] выглядят хорошо, но не целиком в PIP8
4. Я добавил опцию. Однако, почему кто-то связывает лямбды и грацию, мне не понять 😉
5. Да, выглядит не очень просто) Левый первый вариант)
Ответ №2:
Если numpy является опцией, возможно, что-то вроде этого:
import numpy as np goods = np.array([True, False, True, True, False, True, False]) goods[[1,3,4]] ^= True # xor to flip booleans print(goods) # [True True True False True True False]
Understanding and Avoiding Syntax Errors in Python Dictionaries
In Python, there are three main types of errors: Syntax errors, Runtime errors, and Logical errors. Syntax errors can include system errors and name errors. System errors occur when the interpreter encounters extraneous tabs and spaces, given that proper indentation is essential for separating blocks of code in Python. Name errors arise when variables are misspelled, and the interpreter can’t find the specified variable within the code’s scope.
Syntax errors are raised when the Python interpreter fails to understand the given commands by the programmer. In other words, when you make any spelling mistake or typos in your code, it will most definitely raise a syntax error.
It can also be raised when defining data types. For example, if you miss the last curly bracket, “>” when defining a dictionary or capitalize the “P” while trying to print an output, it will inevitably raise a syntax error or an exception.
In this article, we will take a look at one of the most common syntax errors. When trying to define dictionaries, there shouldn’t be any assignment operator, i.e., “=” between keys and values. Instead, you should put a colon , “:” between the two.
Let’s look at the root of the above problem followed by it’s solution.
Causes of Syntax Errors in Python Dictionaries
Python’s syntax errors can happen for many reasons, like using tabs and spaces incorrectly, spelling variables wrong, using operators the wrong way, or declaring things incorrectly. One common mistake is defining dictionaries wrongly by using “=” instead of “:” between keys and values. Fixing these issues usually means double-checking that everything is spelled right and that you are using things like colons, semicolons, and underscores properly.
There can be numerous reasons why you might encounter a syntax error in python. Some of them are:
- When a keyword is misspelled.
- If there are missing parenthesis when using functions, print statements, or when colons are missing at the end of for or while loops and other characters such as missing underscores(__) from def __innit__() functions.
- Wrong operators that might be present at the wrong place.
- When the variable declared is wrong or misspelled.
Differentiating between ‘=’ and ‘==’ in context of Python Dictionaries
In Python and many other programming languages, the single equals sign “=” denotes assignment, where a variable is given a specific value. In contrast, the double equals sign “==” is used to check for equality between two values or variables.
For example, if there are two variables, namely. ‘a’ and ‘b’ in your code, and you want to assign the integer values of 10 and 20 to each, respectively. In this case, you’ll need to use the assignment operator, that is, a single equal to sign(=) in your code in the following way:
But instead, if we want to check whether the values assigned to ‘a’ and ‘b’ are equal using an “if” statement, we will use the double equal to sign (==) such as,
Syntax Rules for Python Dictionaries
In Python, dictionaries are a unique type of data-storing variables. They are ordered and mutable in nature unlike lists. They are assigned in pairs, in the form of keys and values. Each element in a dictionary is indexed by its’ keys. Each value is accessed by keeping track of its respective key. There should be a colon”:” separating the value from its respective key. They are represented by curly braces ‘<>’. Each key and value pair can be separated from one another with commas ‘,’.
They can be assigned in the following manner:
Reproducing the Syntax Error: expression cannot contain assignment, perhaps you meant “==”?
In this case, the problem might arise when instead of using a colon “:”, the interpreter encounters an assignment operator. There is a built in function in Python that can explicitly convert data into dictionaries called dict(). But this function might also cause this problem when the identifier is wrong or when there are other syntax mistakes in the code, such as missing parenthesis at the end of a statement.
Mitigating Syntax Errors in Python Dictionaries
The only straight forward solution to this problem is making sure you spell the keywords and in built functions correctly and remember to use the identifiers such as colons, semicolons and underscores properly.
Try to avoid using the dict() function for creating dictionaries. Instead, use curly braces as much as possible. If using the function is a necessity, make sure you don’t use the assignment operator incorrectly and use parentheses where necessary.
In the following code, there are no exceptions raised because the syntax is correct and the variable has been assigned correctly.
Nowadays, there are built in syntax detectors in IDEs and editors which can highlight syntax errors like this one. You can also use a debugger if necessary.
Key Takeaways: Avoiding Syntax Errors in Python Dictionaries
Having dived into the causes and solutions of Python’s syntax errors, we hope this equips you to write more efficient, error-free code. The intricacies of Python dictionaries need not be a source of worry. With the right practices, you can avoid these errors, optimizing your code and enriching your programming journey.
How will this knowledge influence your approach to using Python dictionaries in future projects?
Running GRASS r.watershed in Python returns SyntaxError: expression cannot contain assignment
I am trying to run r.watershed in my Python script using GRASS . I am trying to put in the appropriate parameters but I keep getting the error: SyntaxError: expression cannot contain assignment, perhaps you meant «==»? Here’s the code. What am I doing wrong here?
import grass.script as gscript def main(): gscript.run_command('g.region', flags='p') gscript.run_command('r.watershed', elevation = 'C:/Projects/TWI/Data/Rivanna/USGS_10M_RCC_mos.tif', depression = 'C:/Projects/TWI/Data/Rivanna/USGS_10M_RCC_mos.tif', flow = None, disturbed_land = None, blocking = None, threshold = None, max_slope_length = None, convergence = 5, memory = 300, -s = True, -m = False, -a = False, -b = False, tci = 'C:/Projects/TWI/Tests/QGIS_Grass/Script/10M/twi_10M_r_watershed_test2.tiff', GRASS_REGION_PARAMETER = None, GRASS_REGION_CELLSIZE_PARAMETER = 0) if __name__ == '__main__': main()
1 Answer 1
In GRASS GIS all maps are stored in a specially formatted database. When you want to use these map layers you refer to them by the GRASS name. You cannot refer to an external Geotiff file within a GRASS module; you need to import it first. In fact, the only GRASS commands that accept a file path to some external file are the import modules r.import , v.import , and the equivalent export modules r.out.gdal and v.out.ogr .
Also note that the threshold parameter is crucial (and required) for watershed analysis. You cannot leave it None .
In your case I would suggest something like:
import grass.script as gscript import os data_dir = "'C:/Projects/TWI/Data/Rivanna" elevation_tif = os.path.join(data_dir, "USGS_10M_RCC_mos.tif") def main(): gscript.run_command('r.import', input=elevation_tif, output="elevation") gscript.run_command('g.region', raster="elevation", flags='ap') gscript.run_command('r.watershed', elevation = "elevation", threshold = 1000, direction = "flowdir", accumulation = "flowacc", basin = "basins", stream = "streams", tci = 'tci', ) if __name__ == '__main__': main()
Again, you need to choose the threshold value carefully. This should create 5 new GRASS raster maps: basins, streams, flow direction, flow accumulation, and topographic wetness.
If you need to export to a Geotiff, then add a call to r.out.gdal .
Python Dictionary Object: SyntaxError: expression cannot contain assignment, perhaps you meant “==”
I am creating a dictionary object, it gets created while I use «Statement 1», however I get an error message while try create a dictionary object using same keys and values with «Statement 2».
Statement 1:
Statement 2:
dmap = dict(0='Mon', 1='Tue', 2='Wed', 3='Thu', 4='Fri', 5='Sat', 6='Sun'
Error message:
File "", line 1 SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
Can someone tell me, why am I allowed to create dictionary with integer keys using Statement 1, but not with Statement 2?
Edited
Using an updated version of Statement 2, I am able to create dictionary object with below code:
dmap = dict(day_0='Mon', day_1='Tue', day_2='Wed', day_3='Thu', day_4='Fri', day_5='Sat', day_6='Sun')
Best Solution
dict is a regular callable which accepts keyword arguments. As per the Python syntax, keyword arguments are of the form identifier ‘=’ expression . An identifier may not start with a digit, which excludes number literals.
keyword_item ::= identifier «=» expression
That dict does by default create a dictionary that accepts arbitrary keys does not change the syntax of calls.