Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Created March 31, 2023 08:52
Show Gist options
  • Save chuongmep/42f7cd8b292aa9c0e3d12254d2099152 to your computer and use it in GitHub Desktop.
Save chuongmep/42f7cd8b292aa9c0e3d12254d2099152 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 1, 0, 2]\n"
]
}
],
"source": [
"lst = [12345,56789,56789,12345,789]\n",
"\n",
"# create a dictionary to map unique values to indices\n",
"value_to_index = {}\n",
"index = 0\n",
"for value in lst:\n",
" if value not in value_to_index:\n",
" value_to_index[value] = index\n",
" index += 1\n",
"\n",
"# replace each value in the list with its corresponding index\n",
"indexed_lst = [value_to_index[value] for value in lst]\n",
"\n",
"print(indexed_lst) # [0, 1, 1, 0]"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 2, 2, 0]\n",
"[2, 0, 1, 2]\n"
]
}
],
"source": [
"lst1 = [12345,56789,56789,12345]\n",
"lst2 = [56789,12345,67890,56789]\n",
"\n",
"# find the unique values in both lists\n",
"unique_values = list(set(lst1 + lst2))\n",
"\n",
"# create a dictionary to map unique values to indices\n",
"value_to_index = {}\n",
"index = 0\n",
"for value in unique_values:\n",
" value_to_index[value] = index\n",
" index += 1\n",
"\n",
"# replace each value in the lists with its corresponding index\n",
"indexed_lst1 = [value_to_index[value] for value in lst1]\n",
"indexed_lst2 = [value_to_index[value] for value in lst2]\n",
"\n",
"print(indexed_lst1) # [0, 1, 1, 0]\n",
"print(indexed_lst2) # [1, 0, 2, 1]"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment