Here are my attempts at a generic solution. First, the setup -
list_1 = [1, 2, 4, 5, 10, 4, 3]
The first two options are pure-python based, while the last two use numerical libraries (numpy and pandas).
Option 1
dict
.get
Generate a mapping
of keys to values. In the list comprehension, query dict.get
-
mapping = {0 : 'v0', 1 : 'v1', 2 : 'v2'}
r = [mapping.get(x % 4, 'v3') for x in list_1]
r
['v1', 'v2', 'v0', 'v1', 'v2', 'v0', 'v3']
Here, 'v3'
is the default value that is returned when the result of x % 4
does not exist as a key in mapping
.
This would work for any arbitrary set of conditions and values, not just the condition outlined in the question (modulo arithmetic).
Option 2
collections
.defaultdict
A similar solution would be possible using a defaultdict
-
from collections import defaultdict
mapping = defaultdict(lambda: 'v3', {0: 'v0', 1: 'v1', 2: 'v2', 3: 'v3'})
r = [mapping[x % 4] for x in list_1]
r
['v1', 'v2', 'v0', 'v1', 'v2', 'v0', 'v3']
This works similar to Option 1.
Option 3
numpy
.char
.add
If you use numpy
, then you might be interested in a vectorised solution involving modulo arithmetic and broadcasted addition -
r = np.char.add('v', (np.array(list_1) % 4).astype('<U8'))
r
array(['v1', 'v2', 'v0', 'v1', 'v2', 'v0', 'v3'],
dtype='<U9')
If you require a list as the final result, you can call r.tolist()
. Note that this solution is optimised for your particular use case. A more generic approach would be achieved with numpy
using np.where
/np.select
.
Option 4
pd
.Series
.mod
+ pd
.Series
.radd
A similar solution would also work with pandas
mod
+ radd
-
r = pd.Series(list_1).mod(4).astype(str).radd('v')
r
0 v1
1 v2
2 v0
3 v1
4 v2
5 v0
6 v3
dtype: object
r.tolist()
['v1', 'v2', 'v0', 'v1', 'v2', 'v0', 'v3']