How to handle a one line for loop without putting it in a List?
Maybe the question is a bit vague, b开发者_StackOverflow社区ut 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.
In addition to shahjapan's reduce you can use this syntax to flatten list.
[legname for cow in listofcows for legname in cow.legnames]
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.
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}
Is this what you're looking for?
'livestream' : [cow.legnames[0] for cow in listofcows]
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])))
精彩评论