简体   繁体   中英

return tuple into strings and why is it only returning the 1st index of list of tuple?

how can I include all in list of tuple?

def convert(list_tup):
    for a,b,c in list_tup:
        return c + ' ' + a + ' ' + b

strings = [('w', 'x','2'), ('y', 'z', '3')]
print(convert(strings))

output is: 2 wx it only returns the 1st index of list of tuple

it is the expected output when i use print(c + ' ' + a + ' ' + b)

expected output:

2 w x 
3 y z

also is there a way i can separate the string without using a string space in return c + ' ' + a + ' ' + b like sep = ' '

Here is how:

def convert(list_tup):
    
    return '\n'.join([' '.join((tup[-1],)+tup[:-1]) for tup in list_tup])

strings = [('w','x','2'), ('y', 'z', '3')]

print(convert(strings))

Output:

2 w x
3 y z

The reason you're getting only "2 wx" is because you have a return statement in the for loop. In the first iteration itself, it returns from the function.

You can directly include a print inside the for loop. Also, instead of ' ' , you can use commas (,)

def convert(list_tup):
    for a,b,c in list_tup:
        print(c, a, b)

strings = [('w', 'x','2'), ('y', 'z', '3')]
convert(strings)

This is happening because of this line:

return c + ' ' + a + ' ' + b

You are causing the function to return after the first iteration .

You could use a list comprehension combined with f strings to do what I think you want.

Try this:

def convert(list_tup):
    return [f'{c} {a} {b}' for a,b,c in list_tup]

strings = [('w', 'x', '2'), ('y', 'z', '3')]

for string in convert(strings):
    print(string)

You cannot put a return inside a loop and expect it to return values repeatedly -- once it returns the first value the function is finished. But if you are trying to generate a sequence of values, you could easily turn it into generator function by using yield instead of return . Then when you call your function you get an object which you can iterate over to get the sequence of values. For example:

def convert(list_tup):
    for a,b,c in list_tup:
        yield c + ' ' + a + ' ' + b

strings = [('w', 'x','2'), ('y', 'z', '3')]
for s in convert(strings):
    print(s)

gives

2 w x
3 y z

Or for example, you could use list to iterate over these values and put them into a list:

print(list(convert(strings)))
['2 w x', '3 y z']

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