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
Related
This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed last year.
import time
while True:
npc=input("Josuke\n\nJotaro Kujo (Part 4)\n\nChoose NPC to talk to.")
if npc=="Josuke" or npc=="josuke":
confirm=input("[Press E to interact.]")
elif npc=="jp4" or npc=="JP4" or npc=="Jp4
Within this code you can see that there are 2 NPCs to interact to. Because there are many ways of addressing the name Jotaro Kujo (Part 4), the if statement has many "or"s, but I want to be able to condense it. Could I use an array to be able to put the possibilities in and then have the if statement identify if the value is within the array? (I haven't completed the code yet, but the problem doesn't require the full code to be completed.)
Yes, you can do it easily using the in operator to check if a particular string is in the list.
as an example:
lst = ["bemwa", "mike", "charles"]
if "bemwa" in lst:
print("found")
And if all the possibilities you want to cover are related to case-insensitivity you can simply convert the input to lower-case or upper-case and compare it with only one possibility.
This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 7 months ago.
For example: I have a list called container. In it are some elements and I want to check if eg. any of them are complex.
container = [1, 0.5, "text", 1j]
if isinstance(container[?], complex):
print("This list has complex elements")
In this example, I could've written container[-1], but is there an universal method?
I could use a for loop, but I'm wondering if there are better ways to do this.
There are many ways to apply something to entire container, e.g.
any(isinstance(element, complex) for element in container)
You could use a list comprehension along with python's any() function:
any([isinstance(x, complex) for x in container])
This would return True if the list has complex numbers.
With pure python I think you would have to explicitly iterate over the list. It can be done with a simple list comprehension:
if any([isinstance(c, complex) for c in container]):
print("List has complex elements")
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.
This question already has answers here:
Python. Will TWO condition checked, If `ONE == True`? [duplicate]
(3 answers)
Closed 5 years ago.
I have a multi-part boolean expression in a piece of python code, part of which involves a call to a random number generator and evaluating an expoenential of a sum of a 2d array. Since this is buried deep in nested loops I want to avoid checking that last part if at all possible, since it's computationally expensive.
if self.B == 0 or (np.sign(self.B) == -sign) or (np.random.rand() < np.exp(-2*sign*self.B*np.sum(cluster))):
do stuff
If either of the first two expression are true, will the random number generator still be called? Or is it guaranteed to evaluate those parts in order and stop once it finds one that is true?
I can always make it explicit by breaking it up, but it seems like something I should probably know anyway.
In if A or B, B is only evaluated if A is false.
This concept is called short circuiting, and you can read a little about it here.
The idea is that you go from left to right until a result is determined. Once that's the case, you stop.
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.