简体   繁体   中英

Return multiple values with generator expression

I have a list

a = ["a", "b", "c"]

I want to create a new list with duplicate values with suffix("_ind").

["a", "a_ind", "b", "b_ind", "c", "c_ind"]

I know it can be achieved using the following function( List with duplicated values and suffix )

def duplicate(lst):
    for i in lst:
      yield i
      yield i + "_ind"

How the same functionality can be achieved using generator expression?. I tried with the following code, But it is not working.

duplicate = (i i+'_ind' for i in a) 

File "<stdin>", line 1
duplicate = (i i+'_ind' for i in a)
            ^
SyntaxError: invalid syntax

采用

duplicate = (j for i in a for j in (i, i+'_ind'))

When yield are used in the function, they return a value of each yield statement. That means, if you have two yields, each yields will return a single value at each step. However, in the generator expression you can't return two values keeping the return value flat, instead you'll have to return it as tuple. But you can flatten the tuple at the time of extracting value. So, for you case, you may do:

>>> a = ["a", "b", "c"]
>>> duplicate = ((i, i+'_ind') for i in a)
#                 ^ return it as a tuple

>>> [i for s in duplicate for i in s]
['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind']

OR, you may use the generator expression as mentioned in Oluwafemi Sule's answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM