繁体   English   中英

将元组返回到字符串中,为什么它只返回元组列表的第一个索引?

[英]return tuple into strings and why is it only returning the 1st index of 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它只返回元组列表的第一个索引

当我使用print(c + ' ' + a + ' ' + b)时,这是预期的 output

预期 output:

2 w x 
3 y z

还有一种方法可以在不使用字符串空间的情况下分隔字符串,返回c + ' ' + a + ' ' + b like sep = ' '

方法如下:

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

你只得到“2 wx”的原因是你在for循环中有一个return语句。 在第一次迭代本身中,它从 function 返回。

您可以直接在 for 循环中包含 print 。 此外,您可以使用逗号 (,) 代替' '

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

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

这是因为这条线:

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

您正在导致 function 在第一次iterationreturn

您可以将list comprehensionf strings结合使用来执行我认为您想要的操作。

尝试这个:

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)

您不能将return放入循环中并期望它重复返回值——一旦它返回第一个值,function 就完成了。 但是,如果您尝试生成一系列值,则可以使用yield而不是return轻松地将其转换为生成器function 。 然后,当您调用 function 时,您会得到一个 object ,您可以对其进行迭代以获得值序列。 例如:

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)

2 w x
3 y z

或者例如,您可以使用list遍历这些值并将它们放入列表中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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