Thenusbible.files.wordpress.com



Random Python Tips:Strings, Lists, Tuples, and Dictionaries are iterablesBe careful when modifying a list or dictionary when looping through itAvoid naming conflicts, especially in OOPData Parsing Random Tips:data = read_csv(fname)[1:]CHANGE STRING DIGITS TO INT/FLOAT WHEN NECESSARYIf comparing values and then sorting into groups, make sure the last group is accounted for, especially if previous group is only added when the next item is evaluatedOOP Random Tips:class ClassName: def __init__(self, name, ..., *args if there are arbitray inputs): self.name = name … self.arbitary_inputs = args #Don’t put star here. This gives a tupleclass ClassName(parent class if inheriting): def __init__(self, name, ..., *args if there are arbitray inputs): super().__init__(name, ..., *args if there are arbitray inputs): #Do not add attributes being inherited from parent … self.arbitary_inputs = args #Don’t put star here. This gives a tuple “{} this is how to return {} a string {}”.format(arg, arg, arg)Random Useful Python StuffCommandResultmap(function, l/t)Maps the function to all elements in a list or tupleUse with list()or tuple() to return as list or tuplefilter(function, l/t)Filters out everything from a list or tuple that returns True in the functionUse with list()or tuple() to return as list or tupleall(l/t)Returns True if all elements of a list or tuple are trueUse this with map to compare all entries to somethingany(l/t)Returns True if any element of a list or tuple is trueUse this with map to compare all entries to somethingmax(l/t)Returns highest value in a list or tuple (See below for dictionary)zip(*arg)Combines elements in corresponding indices of a mixture of lists, tuples, or ranges arguments into one tuple group per index. Stops at the length of shortest argument.Use with list()or tuple() to return as list or tuplefor x,y,… in zip(*arg)Loops through a mixture of lists, tuples, or ranges and stops at the length of the shortest argumentUseful Number FunctionsCommandResultround(float, *decimals)Rounds a float to the given number of decimal place, if not, nearest integer[int(dig) for dig in str(num)]Splits a number into individual digits as entries in a list+,-,*,/,//,%Adds, subtracts, divides, floor divison, remainderfrom math import ceilceil(float)Returns ceiling of floatUseful String FunctionsCommandResults.digit()Returns True if s is a digits.isalpha()Returns True if s is a letters.replace(old, new, *number)Replaces all occurrences of old with new, unless a specified number is givens.join(iterable)Joins all strings in an iterable, separated by sUse s = ‘’ to convert iterable to strings.lower()Changes all characters in s to lowercases.upper()Changes all characters in s to uppercases.split()Splits a string at space and returns a listtuple(s)Returns tuple of individual characters in slist(s)Returns list of individual characters in sUseful Tuple FunctionsCommandResultAdd to Tuplet + eleAdds two tuples together if element is a tuplet + (ele,)Adds tuple with element if element is not a tupleDelete From TupleUse slicingReturns new tupleMake a Copyt[:]Creates a shallow copy of tupleimport copycopy.deepcopy(t)Creates a deep copy of tupleConversionstuple(range(val))Returns a tuple of numbers in a given rangelist(t)Converts tuple to lists.join(t)Joins all strings in a tuple, separated by sUse s = ‘’ to convert tuple to string{x:y for x,y in t}Returns a dictionary of pairs now as key-value pairs{x:y for y,x in t}Returns a dictionary of pairs now as key-value pairs, but swappedUseful List FunctionsCommandResultAdd to Listl.append(ele)Adds an element to the back of the list as a new entryl.extend(ele)Opens apart an iterable and adds to the back of the listl.insert(index, ele)Inserts element into given index of listDelete from Listdel l[index]Removes entry at given index in listl.remove(entry)Removes first occurrence of entry givenl.pop(index)Removes entry at given index in listMake a Copyl.copy()Creates a shallow copy of listl[:]Creates a shallow copy of listimport copycopy.deepcopy(l)Creates a deep copy of listFinding an Entryl.index(entry)Returns index of first occurrence of given entry in list Conversionslist(range(val))Returns a list of numbers in a given rangetuple(l)Converts list to tuples.join(l)Joins all strings in a list, separated by sUse s = ‘’ to convert list to string{x:y for x,y in l}Returns a dictionary of pairs now as key-value pairs{x:y for y,x in l}Returns a dictionary of pairs now as key-value pairs, but swappedSorting a Listl.sort()Sorts a list low to high. If entries are lists/tuples, sorts by index 0l.sort(key, reverse)If entries are lists/tuples, and key is given, sorts based on keykey = lambda x: x[i] to sort based on i-th index key = lambda x: -x[i] to sort based on i-th index, in reversekey = lambda x: (x[i], x[j]) to sort based on i-th index, and then j-th index if i-th indices are the sameIf reverse = True, whole sort is reversedFlattening a Listflat = [i for sublist in l for i in sublist]Flattens a listUseful Dictionary Functions:CommandResultAdding/Deleting Keysd[new_key] = new_valueAdds new_key and new_value to dictionarydel d[key]Deletes key from dictionaryd.pop(key, None)Deletes and returns key from dictionary, None will not raise errorGetting Keys/Values using Values/Keysd[‘key’] Return value associated with the key ‘key’[key for (key,val) in d.items() if val == ‘val’]Returns list of keys associated with the value ‘val’Getting Tuples/Lists of Keys/Valuestuple(d) or tuple(d.keys())Returns tuple of keyslist(d) or list(d.keys())Returns list of keystuple(d.values())Returns tuple of valueslist(d.values())Returns list of valuesGetting Tuples/List of Key-Value pairslist([k,v] for k,v in d.items())Returns list of lists of key-value pairstuple([k,v] for k,v in d.items())Returns tuple of list of key-value pairslist(d.items())Returns list of tuples of key-value pairstuple(d.items())Returns tuple of tuples of key-value pairsGetting max Keys/Values within a Dictionarymax(d) or max(d.keys()Returns largest keymax(d.values())Returns largest valuemax(d, key = lambda x: d[x]) ormax(d.keys(), key = lambda x: d[x])Returns key whose value is the largest*Retuns first key if there are two largest valuesmax(d.values(), key = lambda x: [key for (key,val) in d.items() if val == x])Returns value whose key is the largestFiltering Dictionary Keys/Valuesd = {key:value for key,value in d.items() if f(key)}Returns dictionary of items where f(key) is true*Filter by keyd = {key:value for key,value in d.items() if f(value)}Returns dictionary of items where f(value) is true*Filter by value“Mapping” a Dictionaryd = {f(key):value for key, value in d.items()}Returns dictionary with f() applied to all keysd = {key:f(value) for key, value in d.items()}Returns dictionary with f() applied to all valuesd = {f(key):f(value) for key, value in d.items()}Returns dictionary with f() applied to all keys and valuesMake a Copyd.copy()Creates a shallow copy of dictionaryimport copycopy.deepcopy(d)Creates a deep copy of dictionaryModifying Table Values and Keysd[key] = new_valueReplaces value associated with key with new_valued[new_key] = d.pop(old_key)Replaces old_key with new_key, value unchangedConverting Tuples/Lists to Dictionary, where each entry is a tuple/list pair{x:y for x,y in t/l}Returns dictionary of key-value pairs originally tuple/list pairs{x:y for y,x in t/l}Returns dictionary of key-value pairs originally tuple/list pairsBut order of pair is reversed ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download