Most pythonic way to combine elements of arbitrary lists into a single listBinary index tree optimizationShortest path in imageGenerate set of random numbers and remove lowestProcessing a sequence of additions and deletionsGame where two players take turns picking numbers until a target sum (part 2)Finding line numbers of duplicate lines in a log fileSparse matrix compressed sparse row (CSR) in Python 2.7Python - One-to-many dictionary mappingAppointment Scheduleincrease the efficiency of a matching algorithm
How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?
Plagiarism or not?
How much of data wrangling is a data scientist's job?
Why didn't Miles's spider sense work before?
Can a virus destroy the BIOS of a modern computer?
Detention in 1997
Ambiguity in the definition of entropy
Expand and Contract
Does the Idaho Potato Commission associate potato skins with healthy eating?
Why was the shrinking from 8″ made only to 5.25″ and not smaller (4″ or less)?
When (not how or why) to calculate Big O of an algorithm
Is it inappropriate for a student to attend their mentor's dissertation defense?
ssTTsSTtRrriinInnnnNNNIiinngg
What mechanic is there to disable a threat instead of killing it?
Apex Framework / library for consuming REST services
GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?
Forming a German sentence with/without the verb at the end
Valid term from quadratic sequence?
Am I breaking OOP practice with this architecture?
Avoiding the "not like other girls" trope?
Short story with a alien planet, government officials must wear exploding medallions
How to add frame around section using titlesec?
What about the virus in 12 Monkeys?
Do UK voters know if their MP will be the Speaker of the House?
Most pythonic way to combine elements of arbitrary lists into a single list
Binary index tree optimizationShortest path in imageGenerate set of random numbers and remove lowestProcessing a sequence of additions and deletionsGame where two players take turns picking numbers until a target sum (part 2)Finding line numbers of duplicate lines in a log fileSparse matrix compressed sparse row (CSR) in Python 2.7Python - One-to-many dictionary mappingAppointment Scheduleincrease the efficiency of a matching algorithm
$begingroup$
I have a list of lists which represents the options I can chose from.
I have a sequence of indices which represent which option lists I want to take elements from, and in which order.
E.g. if I have
choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
sequence = [ 2, 0, 1, 1 ]
I want my output to be
[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1
I have found three possible solutions:
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
choice = [ element for i in sequence for element in choices[i] ]
I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.
python performance
$endgroup$
add a comment |
$begingroup$
I have a list of lists which represents the options I can chose from.
I have a sequence of indices which represent which option lists I want to take elements from, and in which order.
E.g. if I have
choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
sequence = [ 2, 0, 1, 1 ]
I want my output to be
[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1
I have found three possible solutions:
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
choice = [ element for i in sequence for element in choices[i] ]
I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.
python performance
$endgroup$
$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08
$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10
$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole listchoice, or would an iterable do? What do you do with it next?
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12
$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13
$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi♦
Jul 10 '14 at 14:30
add a comment |
$begingroup$
I have a list of lists which represents the options I can chose from.
I have a sequence of indices which represent which option lists I want to take elements from, and in which order.
E.g. if I have
choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
sequence = [ 2, 0, 1, 1 ]
I want my output to be
[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1
I have found three possible solutions:
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
choice = [ element for i in sequence for element in choices[i] ]
I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.
python performance
$endgroup$
I have a list of lists which represents the options I can chose from.
I have a sequence of indices which represent which option lists I want to take elements from, and in which order.
E.g. if I have
choices = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
sequence = [ 2, 0, 1, 1 ]
I want my output to be
[7, 8, 9, 1, 2, 3, 4, 5, 6, 4, 5, 6]
#index 2 index 0 index 1 index 1
I have found three possible solutions:
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
choice = [ element for i in sequence for element in choices[i] ]
I would like to know which of these do people find the most pythonic and to know if there are any other elegant solutions.
python performance
python performance
edited 5 mins ago
Community♦
1
1
asked Jul 10 '14 at 14:02
GriffinGriffin
171115
171115
$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08
$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10
$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole listchoice, or would an iterable do? What do you do with it next?
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12
$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13
$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi♦
Jul 10 '14 at 14:30
add a comment |
$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08
$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10
$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole listchoice, or would an iterable do? What do you do with it next?
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12
$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13
$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi♦
Jul 10 '14 at 14:30
$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08
$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08
$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10
$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10
$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list
choice, or would an iterable do? What do you do with it next?$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12
$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list
choice, or would an iterable do? What do you do with it next?$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12
$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13
$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13
$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi♦
Jul 10 '14 at 14:30
$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi♦
Jul 10 '14 at 14:30
add a comment |
4 Answers
4
active
oldest
votes
$begingroup$
Unless I actually needed the whole list at once, I would probably use itertools for this:
from itertools import chain
choice = chain.from_iterable(choices[i] for i in sequence)
If you do need the list, you can still use this with an explicit conversion:
choice = list(chain.from_iterable(choices[i] for i in sequence))
Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.
$endgroup$
add a comment |
$begingroup$
I find neither of your solutions very pythonic.
Using sum to concatenate lists seems like a hack.
Using reduce looks better but still has the problem of making the selection too verbose to read it fast.
The last one is far too much. Understanding what it does takes way too long.
Actually the problem you are solving is two subproblems:
- taking a list of samples from the choices collection
- flattening the resulting list
So the code should be more like
flatten(samples(choices, sequence))
I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).
$endgroup$
$begingroup$
Also, although not deprecated per se,reducehas moved from the built-ins tofunctoolsin 3.x, which could be interpreted as suggesting its use isn't Pythonic.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
1
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to formgenerator expressionsandcomprehensionsof various types:list,set,dict; and he's on record as saying most people usereducewhen they mean to usesum, and I'd agree.
$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
add a comment |
$begingroup$
I agree with @jonrsharpe: Use itertools.chain().
The problem with the first two solutions…
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
is that adding lists does not scale well, if sequence is long.
The third solution…
choice = [ element for i in sequence for element in choices[i] ]
doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.
$endgroup$
add a comment |
$begingroup$
You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.
The "most" pythonic in my opinion would be this:
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
break
choice += choices[choice_index]
For a one-liner? I will wrap it in a function and use that like this for repetitive work.
def generate_choice_list(choices, sequence):
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
return []
choice += choices[choice_index]
return choice
This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f56650%2fmost-pythonic-way-to-combine-elements-of-arbitrary-lists-into-a-single-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Unless I actually needed the whole list at once, I would probably use itertools for this:
from itertools import chain
choice = chain.from_iterable(choices[i] for i in sequence)
If you do need the list, you can still use this with an explicit conversion:
choice = list(chain.from_iterable(choices[i] for i in sequence))
Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.
$endgroup$
add a comment |
$begingroup$
Unless I actually needed the whole list at once, I would probably use itertools for this:
from itertools import chain
choice = chain.from_iterable(choices[i] for i in sequence)
If you do need the list, you can still use this with an explicit conversion:
choice = list(chain.from_iterable(choices[i] for i in sequence))
Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.
$endgroup$
add a comment |
$begingroup$
Unless I actually needed the whole list at once, I would probably use itertools for this:
from itertools import chain
choice = chain.from_iterable(choices[i] for i in sequence)
If you do need the list, you can still use this with an explicit conversion:
choice = list(chain.from_iterable(choices[i] for i in sequence))
Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.
$endgroup$
Unless I actually needed the whole list at once, I would probably use itertools for this:
from itertools import chain
choice = chain.from_iterable(choices[i] for i in sequence)
If you do need the list, you can still use this with an explicit conversion:
choice = list(chain.from_iterable(choices[i] for i in sequence))
Note: this fits pretty close to Nobody's suggestion - here chain.from_iterable is flatten and the generator expression is making the sample.
answered Jul 10 '14 at 14:14
jonrsharpejonrsharpe
13.2k12858
13.2k12858
add a comment |
add a comment |
$begingroup$
I find neither of your solutions very pythonic.
Using sum to concatenate lists seems like a hack.
Using reduce looks better but still has the problem of making the selection too verbose to read it fast.
The last one is far too much. Understanding what it does takes way too long.
Actually the problem you are solving is two subproblems:
- taking a list of samples from the choices collection
- flattening the resulting list
So the code should be more like
flatten(samples(choices, sequence))
I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).
$endgroup$
$begingroup$
Also, although not deprecated per se,reducehas moved from the built-ins tofunctoolsin 3.x, which could be interpreted as suggesting its use isn't Pythonic.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
1
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to formgenerator expressionsandcomprehensionsof various types:list,set,dict; and he's on record as saying most people usereducewhen they mean to usesum, and I'd agree.
$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
add a comment |
$begingroup$
I find neither of your solutions very pythonic.
Using sum to concatenate lists seems like a hack.
Using reduce looks better but still has the problem of making the selection too verbose to read it fast.
The last one is far too much. Understanding what it does takes way too long.
Actually the problem you are solving is two subproblems:
- taking a list of samples from the choices collection
- flattening the resulting list
So the code should be more like
flatten(samples(choices, sequence))
I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).
$endgroup$
$begingroup$
Also, although not deprecated per se,reducehas moved from the built-ins tofunctoolsin 3.x, which could be interpreted as suggesting its use isn't Pythonic.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
1
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to formgenerator expressionsandcomprehensionsof various types:list,set,dict; and he's on record as saying most people usereducewhen they mean to usesum, and I'd agree.
$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
add a comment |
$begingroup$
I find neither of your solutions very pythonic.
Using sum to concatenate lists seems like a hack.
Using reduce looks better but still has the problem of making the selection too verbose to read it fast.
The last one is far too much. Understanding what it does takes way too long.
Actually the problem you are solving is two subproblems:
- taking a list of samples from the choices collection
- flattening the resulting list
So the code should be more like
flatten(samples(choices, sequence))
I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).
$endgroup$
I find neither of your solutions very pythonic.
Using sum to concatenate lists seems like a hack.
Using reduce looks better but still has the problem of making the selection too verbose to read it fast.
The last one is far too much. Understanding what it does takes way too long.
Actually the problem you are solving is two subproblems:
- taking a list of samples from the choices collection
- flattening the resulting list
So the code should be more like
flatten(samples(choices, sequence))
I am no regular user of python so I can't tell you much about library implementations of flatten and samples but I am quite sure that there are many implementations around on the net (not necessarily under these names though).
answered Jul 10 '14 at 14:13
NobodyNobody
4,1871738
4,1871738
$begingroup$
Also, although not deprecated per se,reducehas moved from the built-ins tofunctoolsin 3.x, which could be interpreted as suggesting its use isn't Pythonic.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
1
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to formgenerator expressionsandcomprehensionsof various types:list,set,dict; and he's on record as saying most people usereducewhen they mean to usesum, and I'd agree.
$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
add a comment |
$begingroup$
Also, although not deprecated per se,reducehas moved from the built-ins tofunctoolsin 3.x, which could be interpreted as suggesting its use isn't Pythonic.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
1
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to formgenerator expressionsandcomprehensionsof various types:list,set,dict; and he's on record as saying most people usereducewhen they mean to usesum, and I'd agree.
$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
$begingroup$
Also, although not deprecated per se,
reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
Also, although not deprecated per se,
reduce has moved from the built-ins to functools in 3.x, which could be interpreted as suggesting its use isn't Pythonic.$endgroup$
– jonrsharpe
Jul 10 '14 at 14:35
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
$begingroup$
@jonrsharpe: Given that "Pythonic" often means what GvR thinks, and he doesn't like map/reduce/filter, it's safe to say they aren't pythonic. Nothing that relies on anonymous functions is, really, just look at that syntax.
$endgroup$
– Phoshi
Jul 10 '14 at 15:43
1
1
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form
generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
$begingroup$
Guido doesn't dislike map and filter, he likes them so much that he created a special type of expression that combines them to form
generator expressions and comprehensions of various types: list, set, dict; and he's on record as saying most people use reduce when they mean to use sum, and I'd agree.$endgroup$
– Aaron Hall
Jul 10 '14 at 17:57
add a comment |
$begingroup$
I agree with @jonrsharpe: Use itertools.chain().
The problem with the first two solutions…
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
is that adding lists does not scale well, if sequence is long.
The third solution…
choice = [ element for i in sequence for element in choices[i] ]
doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.
$endgroup$
add a comment |
$begingroup$
I agree with @jonrsharpe: Use itertools.chain().
The problem with the first two solutions…
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
is that adding lists does not scale well, if sequence is long.
The third solution…
choice = [ element for i in sequence for element in choices[i] ]
doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.
$endgroup$
add a comment |
$begingroup$
I agree with @jonrsharpe: Use itertools.chain().
The problem with the first two solutions…
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
is that adding lists does not scale well, if sequence is long.
The third solution…
choice = [ element for i in sequence for element in choices[i] ]
doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.
$endgroup$
I agree with @jonrsharpe: Use itertools.chain().
The problem with the first two solutions…
choice = sum( ( choices[i] for i in sequence ), [] )
choice = reduce( operator.add, ( choices[i] for i in sequence ) )
is that adding lists does not scale well, if sequence is long.
The third solution…
choice = [ element for i in sequence for element in choices[i] ]
doesn't suffer from repeated copying like the first two. However, it's less readable than the itertools.chain version.
answered Jul 10 '14 at 22:16
200_success200_success
131k17157422
131k17157422
add a comment |
add a comment |
$begingroup$
You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.
The "most" pythonic in my opinion would be this:
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
break
choice += choices[choice_index]
For a one-liner? I will wrap it in a function and use that like this for repetitive work.
def generate_choice_list(choices, sequence):
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
return []
choice += choices[choice_index]
return choice
This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.
$endgroup$
add a comment |
$begingroup$
You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.
The "most" pythonic in my opinion would be this:
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
break
choice += choices[choice_index]
For a one-liner? I will wrap it in a function and use that like this for repetitive work.
def generate_choice_list(choices, sequence):
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
return []
choice += choices[choice_index]
return choice
This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.
$endgroup$
add a comment |
$begingroup$
You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.
The "most" pythonic in my opinion would be this:
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
break
choice += choices[choice_index]
For a one-liner? I will wrap it in a function and use that like this for repetitive work.
def generate_choice_list(choices, sequence):
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
return []
choice += choices[choice_index]
return choice
This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.
$endgroup$
You want something to be pythonic? It seems you would like to have a one liner. Simple AND elegant is more pythonic in my opinion.
The "most" pythonic in my opinion would be this:
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
break
choice += choices[choice_index]
For a one-liner? I will wrap it in a function and use that like this for repetitive work.
def generate_choice_list(choices, sequence):
choice = []
for choice_index in sequence:
if choice_index >= len(choices):
return []
choice += choices[choice_index]
return choice
This has the added advantage of eliminating wrong entries with the sequence list, like returning empty list for incorrect sequence list.
answered Jul 11 '14 at 13:50
thiruvenkadamthiruvenkadam
1111
1111
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f56650%2fmost-pythonic-way-to-combine-elements-of-arbitrary-lists-into-a-single-list%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Per the style guide, consider removing the extraneous whitespace inside brackets.
$endgroup$
– jonrsharpe
Jul 10 '14 at 14:08
$begingroup$
@jonrsharpe this per the company style guide, unfortunately.
$endgroup$
– Griffin
Jul 10 '14 at 14:10
$begingroup$
Ah, I see - it's probably worth mentioning that you're following such a thing! Do you need the whole list
choice, or would an iterable do? What do you do with it next?$endgroup$
– jonrsharpe
Jul 10 '14 at 14:12
$begingroup$
@jonrsharpe an iterable is fine.
$endgroup$
– Griffin
Jul 10 '14 at 14:13
$begingroup$
assuming that they all do the same thing, this may be a matter of opinion, or this whole question could fall under "code not written (yet)"
$endgroup$
– Malachi♦
Jul 10 '14 at 14:30