These useful python snippets I've listed have saved me a lot of time, and I hope they'll save you some time as well. Most of these fragments come from finding solutions, finding blogs and StackOverflow answers to similar questions. All of the following code snippets have been tested in Python 3.
Calling an external command in Python
Sometimes you need to invoke an external command from the shell or command prompt, which is easy to implement in Python by using the subprocess module.
You only need to run one command:
Import subprocess
Subprocess.call ([' mkdir ', ' Empty_folder '])
If you want to run a command and output the resulting result:
Import subprocess
Output = Subprocess.check_output ([' ls ', '-l '])
To illustrate, the above call is blocked.
If you run a command built into the shell, such as CD or DIR, you need to specify the tag shell=true:
Import subprocess
Output = Subprocess.call ([' CD ', '/'], shell=true)
For more advanced use cases, you can use the Popen constructor.
Python 3.5 introduces a new run function, which behaves much like call and Check_output. If you're using version 3.5 or later, take a look at run's documentation, which has some useful examples. Otherwise, if you're using a previous version of Python 3.5 or if you want to keep backwards compatibility, the call and check_output snippets above are your safest and simplest choice.
Beautiful printing
Development uses the Pprint module instead of the standard print function, which allows the shell to output more readable information. This makes it easier to read dictionaries and nested objects that are output to the shell.
Import Pprint as pp
Animals = [{' Animal ': ' dog ', ' legs ': 4, ' breeds ': [' Border collie ', ' Pit Bull ', ' Huskie ']}, {' Animal ': ' Cat ', ' legs ': 4, ' Breeds ': [' Siamese ', ' Persian ', ' Sphynx ']}
Pp.pprint (Animals, width=1)
The width parameter specifies the maximum number of characters on a row. Set width to 1 to ensure that the dictionary is printed on separate lines.
grouping data by attribute
Suppose you query a database and get the following data:
data = [
{' Animal ': ' Dog ', ' name ': ' Roxie ', ' Age ': 5},
{' Animal ': ' Dog ', ' name ': ' Zeus ', ' Age ': 6},
{' Animal ': ' Dog ', ' name ': ' Spike ', ' Age ': 9},
{' Animal ': ' Dog ', ' name ': ' Scooby ', ' Age ': 7},
{' Animal ': ' Cat ', ' name ': ' Fluffy ', ' Age ': 3},
{' Animal ': ' Cat ', ' name ': ' Oreo ', ' Age ': 5},
{' Animal ': ' Cat ', ' name ': ' Bella ', ' Age ': 4}
]
Get a list of dogs and a list of cats by animal type grouping. Fortunately, Python's itertools has a groupby function that makes it easy for you to do this.
From Itertools import GroupBy
data = [
{' Animal ': ' Dog ', ' name ': ' Roxie ', ' Age ': 5},
{' Animal ': ' Dog ', ' name ': ' Zeus ', ' Age ': 6},
{' Animal ': ' Dog ', ' name ': ' Spike ', ' Age ': 9},
{' Animal ': ' Dog ', ' name ': ' Scooby ', ' Age ': 7},
{' Animal ': ' Cat ', ' name ': ' Fluffy ', ' Age ': 3},
{' Animal ': ' Cat ', ' name ': ' Oreo ', ' Age ': 5},
{' Animal ': ' Cat ', ' name ': ' Bella ', ' Age ': 4}
]
For key, group in GroupBy (data, Lambda x:x[' animal '):
For thing in group:
Print (thing[' name ') + "is a" + key)
The resulting output is:
Roxie is a dog
Zeus is a dog
Spike is a dog
Scooby is a dog
Fluffy is a cat
Oreo is a cat
Bella is a cat
GroupBy () has 2 parameters: 1, we want to group the data, which in this case is a dictionary. 2. Grouping function: Lambda x:x[' animal '] tells GroupBy function each dictionary is grouped by animal type
Now it's easy to build a list of dogs and a list of cats by using a list derivation:
From Itertools import GroupBy
Import Pprint as pp
data = [
{' Animal ': ' Dog ', ' name ': ' Roxie ', ' Age ': 5},
{' Animal ': ' Dog ', ' name ': ' Zeus ', ' Age ': 6},
{' Animal ': ' Dog ', ' name ': ' Spike ', ' Age ': 9},
{' Animal ': ' Dog ', ' name ': ' Scooby ', ' Age ': 7},
{' Animal ': ' Cat ', ' name ': ' Fluffy ', ' Age ': 3},
{' Animal ': ' Cat ', ' name ': ' Oreo ', ' Age ': 5},
{' Animal ': ' Cat ', ' name ': ' Bella ', ' Age ': 4}
]
Grouped_data = {}
For key, group in GroupBy (data, Lambda x:x[' animal '):
Grouped_data[key] = [thing[' name '] for thing in group]
Pp.pprint (Grouped_data)
Finally, we get an output grouped by animal type:
{
' Cat ': [
' Fluffy ',
' Oreo ',
' Bella '
],
' Dog ': [
' Roxie ',
' Zeus ',
' Spike ',
' Scooby '
]
}
The answer to this question on StackOverflow is very helpful, and when I try to figure out how to group data in the most pythonic way, this article saves me a lot of time.
Remove duplicate elements from a list
Python uses a single line of code to quickly and easily delete duplicate elements in a list (without maintaining the order):
x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
List (set (x))
This method takes advantage of the fact that set is a collection of different objects. However, set does not maintain order, so if you care about the order of objects, use the following techniques:
From collections Import Ordereddict
x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
List (Ordereddict.fromkeys (x))
Index of the For loop that accesses Python
This may be common sense for many people, but it is also frequently asked. Python's built-in enumerate function provides access to indexes and values as follows:
x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
For index, value in enumerate (x):
Print (index, value)
Change the start index by specifying the start parameter of the enumerate function:
x = [1, 8, 4, 5, 5, 5, 8, 1, 8]
For index, value in enumerate (x, start=1):
Print (index, value)
Now the index is from 1 to 9 instead of 0 to 8
Parallel traversal of 2 sets
Use the built-in zip function to traverse 2 lists, dictionaries, etc. at the same time. Here is an example of using the ZIP function to traverse 2 lists at a time:
A = [1, 2, 3]
b = [4, 5, 6]
For (A_val, b_val) in Zip (A, B):
Print (A_val, b_val)
Will output:
1 4
2 5
3 6
Create a copy of an object
Python can use the generic copy function to copy an object. A shallow copy is called by using copy.copy:
Import Copy
New_list = Copy.copy (old_list)
Deep copy:
Import Copy
New_list = Copy.deepcopy (old_list)
This stackoverflow problem is a good explanation for the various methods of copying a list. If you are unfamiliar with the difference between a shallow copy and a deep copy, look at this explanation.
Floating point Division
By converting a molecule or denominator to a float type, you can ensure that floating-point division:
Answer = A/float (b)
Convert strings and dates to each other
A common task is to convert a string to a DateTime object. Using the Strptime function this is easy to do:
From datetime import datetime
Date_obj = Datetime.strptime (' May 2:45PM ', '%B%d%Y%i:%m%p ')
Its inverse operation is to convert a DateTime object to a formatted string, using the Strftime function on a DateTime object:
From datetime import datetime
Date_obj = DateTime.Now ()
date_string = Date_obj.strftime ('%B%d%Y%i:%m%p ')
For a list of formatting codes and their purpose, view official documents
Parse the JSON file and write an object into the JSON file
Use the load function to parse a JSON file and build a Python object. Suppose you have a file called Data.json that includes the following data:
{
"Dog": {
"Lives": 1,
"Breeds": [
"Border Collie",
"Pit Bull",
"Huskie"
]
},
"Cat": {
"Lives": 9,
"Breeds": [
"Siamese",
"Persian",
"Sphynx"
]
}
}
Import JSON
With open (' Data.json ') as Input_file:
data = Json.load (input_file)
Now that data is an object, you can manipulate it like any Python object:
Print (data[' cat ' [' lives '])
Output:9
You can use the dump function to write a dictionary in Python into a JSON file:
Import JSON
data = {' dog ': {' legs ': 4, ' breeds ': [' Border collie ', ' Pit Bull ', ' Huskie ']}, ' cat ': {' legs ': 4, ' breeds ': [' Siamese ', ' P Ersian ', ' Sphynx '}}
With open (' Data.json ', ' W ') as Output_file:
Json.dump (data, output_file, indent=4)
The indent parameter is beautiful to print a JSON string so that the output is easier to read. In this case, we specify a indentation of 4 spaces.
Useful Python Code Snippets