Message314881
It is pretty trivial to concatenate a sequence of strings:
''.join([str1, str2, ...])
Concatenating a sequence of lists is for some reason significantly more convoluted. Some current options include:
sum([lst1, lst2, ...], [])
[x for y [lst1, lst2, ...] for x in y]
list(itertools.chain(lst1, lst2, ...))
The first one being the less recomendable but more intuitive and the third one being the faster but most cumbersome (see https://stackoverflow.com/questions/49631326/why-is-itertools-chain-faster-than-a-flattening-list-comprehension ). None of these looks like "the one obvious way to do it" to me. Furthermore, I feel a dedicated concatenation method could be more efficient than any of these approaches.
If we accept that ''.join(...) is an intuitive idiom, why not provide the syntax:
[].join([lst1, lst2, ...])
And while we are at it:
().join([tpl1, tpl2, ...])
Like with str, these methods should only accept sequences of objects of their own class (e.g. we could do [].join(list(s) for s in seqs) if seqs contains lists, tuples and generators). The use case for non-empty joiners would probably be less frequent than for strings, but it also solves a problem that has no clean solution with the current tools. Here is what I would probably do to join a sequence of lists with [None, 'STOP', None]:
lsts = [lst1, lst2, ...]
joiner = [None, 'STOP', None]
lsts_joined = list(itertools.chain.from_iterable(lst + joiner for lst in lsts))[:-len(joiner)]
Which is awful and inefficient (I am not saying this is the best or only possible way to solve it, it is just what I, self-considered experienced Python developer, might write). |
|
Date |
User |
Action |
Args |
2018-04-03 14:33:53 | Javier Dehesa | set | recipients:
+ Javier Dehesa |
2018-04-03 14:33:53 | Javier Dehesa | set | messageid: <1522766033.22.0.467229070634.issue33214@psf.upfronthosting.co.za> |
2018-04-03 14:33:53 | Javier Dehesa | link | issue33214 messages |
2018-04-03 14:33:53 | Javier Dehesa | create | |
|