Devone
Devone

Reputation: 175

How to put generator expressions as input to Python's join method?

How do I put several generator expressions as input to Python's join method? I tried the following which don't work. Is there a difference when using Python 2.x and 3.x? My exact version is Python 2.7.12.

def productList(self, obj):
    return ", ".join([w.name for w in obj.someProducts.all()],[w.code 
                      for  w in obj.someProducts.all()])

and without the []

    def productList(self, obj):
        return ", ".join(w.name for w in obj.someProducts.all(),w.code 
                         for  w in obj.someProducts.all())

input:

Product table
    Name:  Char;
    Code:  Char;

output:

name1code1, name2code2

Upvotes: 1

Views: 177

Answers (2)

Bahrom
Bahrom

Reputation: 4862

If you want to display name and code, you just need to combine them, you don't need two generators.

', '.join(w.name + ':' + w.code for w in obj.someProducts.all())

Or string formatting:

', '.join('{name}: {code}'.format(name=w.name, code=w.code) for w in obj.someProducts.all())

Or another join (not recommended, unless you can give it a generator - creating another list is a waste, but this demonstrates how you can nest joins)

', '.join(':'.join([w.name, w.code]) for w in obj.someProducts.all())

On a side note, Python 3.6 introduces Literal String Interpolation, which means you should be able to do something like this (I'll test this at home, since I don't have 3.6 at work; could someone verify this actually works. Let me know if it doesn't, I'll remove it):

', '.join(f'{w.name}: {w.code}' for w in obj.someProducts.all())

Upvotes: 2

Or Duan
Or Duan

Reputation: 13840

Give it a try:

', '.join('{}{}'.format(w.name, w.code) for w in obj.someProducts.all())

I just made the w.name and w.code one string, that way you don't need 2 lists. Change the format as you wish.

Upvotes: 2

Related Questions