Python multiple elif alternatives [duplicate] - python

This question already has answers here:
What is the Python equivalent for a case/switch statement? [duplicate]
(2 answers)
Closed 4 years ago.
I have a script which needs to iterate through thousands of various different, but simple options.
I can use if...elif to iterate through them, but am wondering if there is a faster / better option than thousands of elifs. For example
if something == 'a':
do_something_a
elif something == 'b':
do_something_b
elif something == 'c':
do_something_c
elif something == 'd':
do_something_d
...
A thousand more elifs
...
else:
do_something_else
The thing I will be doing will usually be running a function of some kind.

you can use a dictionary to control mutliple possible logical paths:
def follow_process_a():
print('following a')
def follow_process_b():
print('following b')
keyword_function_mapper =
{'a' : follow_process_a ,
'b' : follow_process_b,
}
current_keyword = 'a'
run_method = keyword_function_mapper[current_keyword]
run_method()

you can use a dictionary for that in this way:
def do_something_a():
print 1
def do_something_b():
print 2
dict = {'a': do_something_a, 'b': do_something_b}
dict.get(something)()

What I would recommend is to create a dictionary which maps the somethings to their respective function. Then you can apply this dictionary to the data.
More information: https://jaxenter.com/implement-switch-case-statement-python-138315.html
(Dictionary Mapping)

Related

How to sort list that i get from os.listdir(path) [duplicate]

This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 1 year ago.
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
sorted(a), sorts items in same way as seen in a list
a.sort() also sort list in that way. Is it possible that 'suit10.png' and 'suit12.png' go on the end of list?
Use custom sort as follows:
from functools import cmp_to_key
def cmp_items(a, b):
if int(a.split('suit')[1].split('.png')[0]) > int(b.split('suit')[1].split('.png')[0]):
return 1
elif int(a.split('suit')[1].split('.png')[0]) == int(b.split('suit')[1].split('.png')[0]):
return 0
else:
return -1
cmp_key = cmp_to_key(cmp_items)
a = [
'suit1.png',
'suit10.png',
'suit2.png',
'suit12.png',
'suit3.png',
'suit4.png',
'suit5.png',
'suit6.png',
'suit7.png',
'suit8.png',
]
a.sort(key = cmp_key)
print(a)
Both the sorted function and the list.sort method take an optional key argument which dictates how items are to be sorted. Its value is to be a function that takes a member of the list as an argument and returns a value (usually a number). If a and b are elements of the list, then a will be placed before b if func(a) < func(b).
So, in this case, you could do
a.sort(key=lambda x : int(x[4:].split('.')[0]))

Check if statement true for all list items [duplicate]

This question already has answers here:
Check if any value of a dictionary matches a condition [duplicate]
(2 answers)
Closed 3 years ago.
I have the following dictionary:
dictionary = {'A':0, 'B':0, 'C':0, 'D':0}
I would like to check if all the values stored by the dictionary keys are zero and then execute some code. What I had in mind is something like:
if (dictionary[k] == 0 for all k in dictionary.keys()):
# do something
What I am currently doing is:
if (dictionary['A'] == 0 and dictionary['B'] == 0 and dictionary['C'] == 0 and dictionary['D'] == 0):
# do something
This seems very inefficient if my dictionary grows larger. Is there any way I could check a condition for all keys and demand all of them to be simultaneously true?
Something like this should work, not very short but nice and readable
def check(dictionary):
for value in dictionary.values():
if value != 0:
return False
return True
if check({'A':0, 'B':0, 'C':0, 'D':0}):
#do something
Check this function that can make your code look clean and you can change params as you wish.
# function that return True if all your dictionary values are equal to 0 and false if any value has a different value
def check(dictionary, val):
for key in dictionary:
if dictionary[key]!= val:
return False
return True
if check(dictionary,0):
#do something

Call multiple dictionaries who names involve i in a loop? [duplicate]

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
I would like to call multiple dictionaries using a for loop. I am unsure how to call multiple dictionaries properly, and I can't figure out if its possible using concatenation. The code below should explain my thinking even though the print statement is incorrect.
stat0 = {}
stat0["bob"] = 0
stat1 = {}
stat1["bob"] = 0
stat2 = {}
stat2["bob"] = 0
for i in range(3):
print(stat(i))
How about putting them in a collection, and then getting value generically:
for hm in [stat0, stat1, stat2]
print(hm["bob"])
Instead of naming your dictionaries, just put them into another dictionary:
#UNTESTED
stat = { 0: stat0, 1: stat1, 2: stat2 }
for i in range(3):
print(stat[i])
Or, use an iterative style more appropriate for dict:
#UNTESTED
for i, d in stat.items():
print(i, d)

if/else statements vs dictionary

If I were to write a statement using dictionary instead of an else statement, how would that be? For example, say I have
def determineRank(years):
if years == 1:
return "Freshman"
elif years == 2:
return "Sophmore"
elif years == 3:
return "Junior"
else:
return "Senior"
If I were to rewrite this using dictionary, it would be
rank = {"Freshman":1, "Sophmore":2, "Junior":3, "Senior", ???}
what number would I write for the else?
Use .get method with default value as second argument:
rank = {1: 'Freshman', 2: 'Sophmore', 3: 'Junior'}
rank.get(years, 'Senior')
You can use dictObject.get(key, defaultValue).
So, the equivalent to your function would be:
rank = {1: "Freshman", 2: "Sophmore", 3:"Junior"}.get(year, "Senior");
Note that the key/value pairs of the dictionary is reversed.
Just to expand upon what's already been posted here, using dict.get won't raise a KeyError when the key, e.g. 'Senior', isn't already in the dictionary.
You could also do something like this, utilizing the ternary operator to check whether a given year is already a key in rank:
rank = {1: "Freshman", 2: "Sophomore", 3: "Junior"}
year = 4
year_rank = rank[year] if year in rank else "Senior"
year_rank will be "Senior"
I think the dict.get method is a bit better, though.

ordering a list python list of objects [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 6 years ago.
I have a list containing Student objects with the following attributes: name, hours and qpoints. The list is stored in the variable data. Why am I getting a None return in the following? In other words, data.sort(key = Student.gpa) returns None, even though there is a method returning the gpa in the Student class. I have imported the Student class in my code.
def choiceInput(data):
choice = input('Enter method of sorting <GPA>, <Name>, or <Credits>: ')
choice = choice[0].lower()
if choice == 'g':
return data.sort(key = Student.gpa)
elif choice == 'n':
return data.sort(key = Student.getName)
else:
return data.sort(key = Student.getpPoints)
sort sorts a list in-place and returns None. If you print data after calling sort you'll find it sorted as you expected.

Categories