Adding Lists Elements to 'Mega List'
Let's say I have a list somewhere called majorPowers
which contain these two lists:
axis=["germany","italy","japan"]
allies=["russia","uk","us"]
I'd like to insert each of the elements of these lists, into a new mega-list. I'm currently doing this:
>>> temp = []
>>> temp = [ww2.append(t) for t in majorPowers]
>>>ww2
[['germany','italy','japan'],['russia','uk','us']]
How do I adjust this to not use the temp
and to insert the individu开发者_JS百科al elements into ww2
instead of the lists themselves(axis
and allied
).
Also, would the new mega-list itself be classed as a comprehensive list, or the process of making it?
EDIT:
Please note I do not want to do:
for a in list1:
for b in a:
c.append(b)
@S.Lott. I understand your point. However I'm trying to learn some of the tricks in Python, instead of the standard way I'd usually do things. This is just to open my mind to Python a little more!
It is good that you ask this question, because it is bad form to misuse list
comprehensions like that. The code you show uses append
, not to generate the
elements of temp
, but because of its side effects. Avoid side effects in list
comprehensions!
So, there are a couple of things you can do. First, you can use
itertools.chain
:
>>> from itertools import chain
>>> list(chain(*mayorPowers))
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Instead of passing the elements of mayorPowers
as individual arguments to chain
, you can also use itertools.chain.from_iterable
:
>>> list(chain.from_iterable(mayorPowers))
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Or you can use extend
:
>>> ww2 = []
>>> for mp in mayorPowers:
... ww2.extend(mp)
...
>>> ww2
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Or sum
(I like this one most, I suppose):
>>> sum(mayorPowers, [])
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
Or, to be a little crazy (uses functools.reduce
and operator.add
),
>>> from functools import reduce
>>> from operator import add
>>> reduce(add, mayorPowers)
['germany', 'italy', 'japan', 'russia', 'uk', 'us']
from itertools import chain
ww2 = list(chain.from_iterable(majorPower))
try extend
for t in majorPowers: ww2.extend(t)
or
sum(majorPowers,[])
I would use reduce:
from operator import add
ww2 = reduce(add, majorPowers)
精彩评论