Pythonic way to combine for-loop and if-statement
You can use generator expressions like this:
gen = (x for x in xyz if x not in a)
for x in gen:
print(x)
Pythonic way to combine two FOR loops and an IF statement?
Is there a way to write it in one line
Yes.
or in a Pythonic way?
What you have currently is already the most Pythonic way, no need to change anything here.
How can I combine a conditional with a for loop in Python?
if you want to filter out all the empty sub list from your original sub lists, you will have to do something like below. this will give you all the non empty sub list.
print([sublist for sublist in sublists if sublist])
*edited for syntax
Python for and if on one line
You are producing a filtered list by using a list comprehension. i
is still being bound to each and every element of that list, and the last element is still 'three'
, even if it was subsequently filtered out from the list being produced.
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
for elem in my_list:
if elem == 'two':
break
If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next()
function and a generator expression:
i = next((elem for elem in my_list if elem == 'two'), None)
which will set i
to None
if there is no such matching element.
The above is not that useful a filter; your are essentially testing if the value 'two'
is in the list. You can use in
for that:
elem = 'two' if 'two' in my_list else None
If statement on for-loop on strings not working despite meeting condition
In Python, bool(-1)
evaluates to True
.
The documentation of the str.find
method says if the string is not found, then it returns -1
Hence, no matter if you find or not the needles you are looking for, your condition will always evaluates to True
.
You may consider testing positivity of the result, or using the similar index
method that raises an exception on failure.
Is there a more efficient way instead of multiple FOR loops and IF statements?
FilesName = ['01-01-2001 Active File Name.xlsx', '01-01-2001 Inactive File Name.xlsx']
FinalName = ['01-01-2001 Active File Name--CORRECTION1.xlsx']
# Helper function to clean up the splitting
get_base_name = lambda x: x.split('.',1)[0].split('--', 1)[0]
# Remove the two first loops by checking for base name matches
# using set intersection
filesName_base = {get_base_name(x) for x in FilesName}
finalName_base = {get_base_name(x) for x in FinalName}
files_to_change_base = filesName_base.intersection(finalName_base)
# Potential candidates of files to be changed
files_to_change = [x for x in FilesName if get_base_name(x) in files_to_change_base]
# No need to call this on each iteration of the inner loop
files_in_dir = set(os.listdir(src))
for file_to_change in files_to_change:
if file_to_change in files_in_dir:
# rename files
os.rename(os.path.join(src, item1), os.path.join(src, item2))
# move files
shutil.move(os.path.join(src, item2), os.path.join(dst, item2))
else :
logger.error(error_message)
raise ValueError(error_message)
Edit: Removed another for loop by just looping once and checking if the files are in the directory. files_in_dir
is moved into a set because set membership is a O(1) operation as opposed to O(n).
Need help understanding a specific type of for loop
It's called a list comprehension if it's in brackets []
:
This:
new_list = [x for x in my_list if x in other_list]
Is equivalent to this:
new_list = []
for x in my_list:
if x in other_list:
new_list.append(x)
If it's in parentheses ()
it's called a generator:
This:
new_list = (x for x in my_list if x in other_list)
Is sort of equivalent to this:
def foo():
for x in my_list:
if x in other_list:
yield x
new_list = foo()
You might want to read this question and answer to understand more about generators and yielding functions.
What is the most elegant Pythonic way to write an 'if-statement' within a loop?
for sample in (elt for elt in samples if elt["something"] is None):
sample["something"] = "something_else"
Note use of generator expression to not build another in-memory list, though this might be unnecessary.
I also would not use explicit None check either, unless empty collections, strings or 0 should be considered "truthy" values -- often they aren't, with the exception of zero. if not foo
reads IMO better than if foo is not None
. If this is your case too, you could do just
for sample in samples:
sample["something"] = sample["something"] or "something_else"
Then again I wouldn't probably bother, original would be good enough for me, and like suggested in comments, using or
shortcut could be a tad hacky (in a bad way) for some readers.
Related Topics
Tkinter Grid_Forget Is Clearing the Frame
Return Multiple Columns from Pandas Apply()
How to Read Datetime Back from SQLite as a Datetime Instead of String in Python
Can Pandas Plot a Histogram of Dates
Running Bash Script from Within Python
Python Imaging Library - Text Rendering
Run Powershell Function from Python Script
Double Precision Floating Values in Python
Installing Numpy and Scipy on 64-Bit Windows (With Pip)
Class Variables Is Shared Across All Instances in Python
Call Class Method from Another Class
How to Share Numpy Random State of a Parent Process with Child Processes
Format Strings VS Concatenation
Can't Open Lib 'Odbc Driver 13 for SQL Server'? Sym Linking Issue