How to handle a one line for loop without putting it in a List?

Question:

Maybe the question is a bit vague, but what I mean is this code:

'livestream' : [cow.legnames for cow in listofcows]

Now the problem is cow.legnames is also a list so I will get a list in a list when I try to return it with Json. How should I make it to return a single list.

This is the json that would be returned.

'livestream' : [['blue leg', 'red leg']]

I hope the code explains what my question is.

Asked By: Sam Stoelinga

||

Answers:

From my understanding, you have something like this:

class Cow(object):
    def __init__(self, legnames):
        self.legnames = legnames

listofcows = [Cow(['Red Leg', 'Blue Leg']), 
              Cow(['Green Leg', 'Red Leg'])]

It’s easiest extend a temporary list, like this:

legs = []

# As @delnan noted, its generally a bad idea to use a list
# comprehension to modify something else, so use a for loop
# instead.
for cow in listofcows:
    legs.extend(cow.legnames)


# Now use the temporary legs list...
print {'livestream':legs}
Answered By: Joe Kington

The name listofcows implies there may be, possibly in a distant future, several cows. Flattening a list of list with more than one item would be simply wrong.

But if the name is misleading (and why a one-lement list anyway, for that matter?), you have several options to flatten it.

Nested list comprehension: [legname for cow in listofcows cow.legnames for legname in cow.legnames]

Getting the first item: [your list comprehension][0]

And very likely some useful thingy from the standard library I don’t remember right now.

Answered By: user395760

Is this what you’re looking for?

'livestream' : [cow.legnames[0] for cow in listofcows]
Answered By: Adam Nelson

you can try reduce,
'livestream' : reduce(lambda a,b:a+b,[cow.legs for cow in listofcows])

if you need unique legs use set

'livestream' :list(set(reduce(lambda a,b:a+b,[cow.legs for cow in listofcows])))

Answered By: shahjapan

In addition to shahjapan’s reduce you can use this syntax to flatten list.

[legname for cow in listofcows for legname in cow.legnames]
Answered By: Odomontois

You could also use chain.from_itterable from python itertools Consider the following example:

from itertools import chain

list(chain.from_iterable(cow.legnames for cow in listofcows))

See also chain.from_iterable from the python documentation.

Answered By: Lady Bug
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.