Regular Expression ".{}." in Python List Comprehensions [duplicate] - python

This question already has answers here:
What does {0} mean in this Python string?
(6 answers)
Closed 3 years ago.
I'm reviewing code in the popular Deep learning with Python book and came across. The latter part of the code eventually copies 1000 cat images to a directory, and this line stores the file names to fnames.
fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]
Can someone explain how the syntax works, particularly .{}. in this statement? I have used list comprehension in the past, but I'm not following how this line works.

There is no regular expression here. str.format will replace {} with its argument, that's all. There are other ways to use str.format, but that's what it does here. So for each of the thousand numbers generated in range, the comprehension produces one string that is the result of formatting the number via the filename pattern.

Related

How to format a string in Python source code for improved readability [duplicate]

This question already has answers here:
How do I split the definition of a long string over multiple lines?
(30 answers)
How can I split up a long f-string in Python?
(2 answers)
Closed 10 months ago.
I'm building a rather long file path, like so:
file_path = f"{ENV_VAR}/my_dir/{foo['a']}/{foo['b']}/{bar.date()}/{foo['c']}.json"
This is a simplified example. The actual path is much longer.
To make this line shorter and more readable in code, I have tried the following:
file_path = f"{ENV_VAR}/my_dir\
/{foo['a']}\
/{foo['b']}\
/{bar.date()}\
/{foo['c']}.json"
This works but also affects the actual string in my program.
More specifically, the linebreaks are added to the string value itself, which is undesirable in this case. I only want to change the formatting of the source code.
Is it possible to format the string without affecting the actual value in my program?

This python string sorting works but it shouldn't. Should it? [duplicate]

This question already has answers here:
Python Sort() method [duplicate]
(3 answers)
Closed 2 years ago.
Taking an intro to python course, the following code sorts the string words appropriately, but the function does not return sortString, so I'm not understanding why the output is correct. Can you please help me understand?
def sort_words(string):
splitString = string.split()
sortString = splitString.sort()
return splitString
print(sort_words('python is pretty cool'))
Python .sort() returns None, much like print() does. list.sort() works in place - meaning the list is sorted without needing to assign it to another variable name.

Python array confusion [duplicate]

This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 4 years ago.
I'm a python newbie. I come from a C/C++ background and it's really difficult for me to get my head around some of python's concepts. I have stumbled upon this block of code which just plain confuses me:
file_names = [os.path.join(label_directory, f)
for f in os.listdir(label_directory)
if f.endswith(".ppm")]
So, it's an array that joins label_directory with a variable f (both strings), which is initially uninitialized. The for loop then populates the variable f if the condition f.endswith(".ppm") is true.
Now, from my C/C++ perspective I see this:
A for loop that has an if statement that returns True or False. Where is the logic that excludes all the files that don't end with ".ppm" extension?
This syntax is called list comprehension. It constructs a list by evaluating expression after the opening square bracket for each element of the embedded for loop that meets criteria of the if.
This is called a list comprehension. Python defines list comprehensions as
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.
Syntactically, the code you gave is the same as
file_names = []
for f in os.listdir(label_directory):
if f.endswith(".ppm"):
file_names.append(os.path.join(label_directory, f))
If you want to learn more about list comprehensions, you can find out more here: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Joining Lists and Splitting Strings [duplicate]

This question already has answers here:
Why is it string.join(list) instead of list.join(string)?
(11 answers)
Closed 7 years ago.
I have some previous experience with C++ and just getting started up with Python. I read this text from Dive into Python :
In my experience, a general idea is, if you want to perform an operation on object 'O', you call a method on that object to do it.
Eg. If I have a list object, and I want to get summation of all elements, I would do something like :
listObject.getSumOfAllElements()
However, the call given in above book excerpt looks a little odd to me. To me this would make more sense :
return (["%s=%s" % (k, v) for k, v in params.items()]).join(";")
i.e. join all the elements of the list as a string, and here, use this parameter ';' as a delimiter.
Is this a design difference or just syntactically a little different than what I am thinking ?
Edit:
For completion, the book says this a little later :
Is this a design difference or just syntactically a little different than what I am thinking?
Yes, I think it is by design. The join function is intentionally generic, so that it can be used with any iterable (including iterator objects and generators). This avoids implementing join for list, tuple, set etc separately.

python3 for loop dictionary [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
whats another way to write python3 zip
whats a better way to write these things I was introduced to these codes but I am not used to seeing them these ways:
(alla,allc,) = (set(s) for s in zip(*animaldictionary.keys()))
how else can you write this
print('\n'.join(['\t'.join((c,str(sum(animaldictionary.get(ac,0)
for a in alla
for ac in ((a,c,),))//12)))
for c in sorted(allc)]))
I'll update my answer with a more comprehensive (no pun intended) result once I get home and have more time to wrap my head around this interesting set of comprehensions. For now you will want to check out the following:
List Comprehensions
Nested List Comprehensions
Sets And Set Comprehensions

Categories

Resources