Incrementing a counter while assigning it in python

2024/11/18 8:26:19

Is it possible to do the following in python somehow?

nodename = 'node%s' % (++num if ct[0] != 'J' else num)

Or do I need to first do the increment and the assign it on the next line:

if ct[0] != 'J':num += 1nodename = 'node%s' % num
Answer

Python 3.8+ has the walrus operator, which allows you to assign to a variable within an expression. The expression var := expr assigns the value of expr to var, and results in that same value.

This means the pre-increment operator ++var can be simulated in Python by var := var + 1. This increments var and the result is the new, incremented value of var. This seems to be the behaviour you are looking for.

In languages which have these operators, the post-increment operator var++ has different behaviour; it increments var, but the value of the expression var++ is the old, un-incremented value of var. From your code sample, this doesn't seem to be the behaviour you're looking for, but for completeness, it can be simulated in Python by (var, var := var + 1)[0]. This evaluates to a tuple containing the old value of var and the new value of var after doing the increment, and then gets the first component of that tuple (i.e. the old, un-incremented value).

That said, I would recommend against using the former, and strongly recommend against the latter, since it's highly non-idiomatic in Python. If you want to do two different things (i.e. increment num and format a string), it is more readable and understandable if you do them separately.

https://en.xdnf.cn/q/120096.html

Related Q&A

Append two arrays together into one? (Numpy/Python)

I currently have an array of strings and Im trying to join it together with another array of strings to form a complete word to do some web parsing. For example:`Var1 [A B C, .... ....] Var2 …

Python 2.7 Isolate multiple JSON objects in a string

Ive to parse a text file that contains different kind of data. The most challenging is a line that contains three different JSON object (strings) and other data between them. Ive to divide the Json da…

pass different C functions with pointer arrays as the function argument to a class

I am trying to pass different functions which have pointers as arguments to a python function. One example of the input function as input parameter is the given normal function: Sample.pyxfrom cpython …

dynamic filter choice field in django

I am using django-filter to filter results on a page. I am able to use static choice filters like this:filters.pyFILTER_CHOICES = ( (, All States), (AL, Alabama), (AK, Alaska), (AZ, Arizona), #and so f…

How to print a table from a text file and fill empty spaces?

I have the following table in a txt file:|Client | Container weight | Country of Origin | Product code ||S4378 | 450 Ton | China | 457841 || | 350 Ton | Japan…

Open a file in python from 2 directory back

I want to read a file from 2 folders back.. with open(../../test.txt, r) as file:lines = file.readlines()file.close()I want to read from ../../ two folders back. but not work.. How i can do that ?

Do string representations of dictionaries have order in Python 3.4?

I know dictionaries themselves in Python do not have order. However, Im rather curious if when you call str() on a dictionary if it is always in the same order. It appears to be sorted (by key), no mat…

BeautifulSoup Scraping Results not showing

I am playing around with BeautifulSoup to scrape data from websites. So I decided to scrape empireonlines website for 100 greatest movies of all time. Heres the link to the webpage: https://www.empireo…

How to verify username and password from CSV file in Python?

I am doing a Python project where I have to verify my username and password from a csv file where the first two rows and columns have the username and password as hi.Current Code: answer = input("…

adding validation to answer in quiz gives wrong answers

I am a complete novice with Python and working on a multiple choice quiz that reads questions from a file and keeps a score that then writes to a file. Everything was working perfectly until I added v…