Skip to content

Instantly share code, notes, and snippets.

@travishen
Created August 26, 2019 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travishen/a26e4f02087cdaeeb07aa3d612f4ecef to your computer and use it in GitHub Desktop.
Save travishen/a26e4f02087cdaeeb07aa3d612f4ecef to your computer and use it in GitHub Desktop.
delegate generator recursively
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from collections import Sequence\n",
"\n",
"def flatten(curr_item):\n",
" is_seq = isinstance(curr_item, Sequence)\n",
" is_single_str = isinstance(curr_item, str) and len(curr_item) == 1\n",
" if is_seq and not is_single_str:\n",
" for item in curr_item:\n",
" yield from flatten(item)\n",
" else:\n",
" yield curr_item "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'd', 'o', 'n', 'e']"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"gen = flatten([[[1, 2, 3], [4, 5]], [6, 7, 8], [9, [10, 'done']]])\n",
"list(gen)"
]
}
],
"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.6.8"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment