Ben Chuanlong Du's Blog

It is never too late to learn.

Sort Collections in Python

Tips

  1. You can use the built-in function sorted to sort any iterable collection. It always a (new) list containing sorted data. Some mutable collections (e.g., list) have thee method sort to sort elements in-place. Both sorted and Collection.sort accept an argument key for specifying customized sorting criteria.

Sort a List

Convert a Tensor to a Numpy Array or List in PyTorch

Tips

There are multiple ways to convert a Tensor to a numpy array in PyTorch. First, you can call the method Tensor.numpy.

my_tensor.numpy()

Second, you can use the function numpy.array.

import numpy as np
np.array(my_tensor)

It is suggested that you use the function numpy.array to convert a Tensor to a numpy array. The reason is that numpy.array is more generic. You can also use it to convert other objects (e.g., PIL.Image) to numpy arrays while those objects might not have a method named numpy

Hands on the datetime Module in Python

Comment

A Datetime object cannot be compared with a string directly. However, pandas Series of datetime objects can be compared with string date directly (both by operators and methods). The comparison is done by parsing the string to a datetime object. An exception will be thrown if the string cannot be parsed into a datetime object.