Sam Stoelinga
Sam Stoelinga

Reputation: 5021

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

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.

Upvotes: 1

Views: 4460

Answers (6)

LadyBug
LadyBug

Reputation: 71

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.

Upvotes: 0

Odomontois
Odomontois

Reputation: 16328

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

[legname for cow in listofcows for legname in cow.legnames]

Upvotes: 10

shahjapan
shahjapan

Reputation: 14355

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])))

Upvotes: 0

Joe Kington
Joe Kington

Reputation: 284770

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}

Upvotes: 1

Adam Nelson
Adam Nelson

Reputation: 8090

Is this what you're looking for?

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

Upvotes: 0

user395760
user395760

Reputation:

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.

Upvotes: 2

Related Questions