功能不打印所需的输出

时间:2017-03-06 21:01:38

标签: python function tuples

我遇到创建一个带有元组列表的函数然后返回一个字符串的问题,该字符串是每个元组的第一个字符。下面是我当前的代码,但没有发生任何事情,我没有得到语法错误。任何帮助将不胜感激。

lst_of_tups = ([('hello', 'all'), ('music', 'playing'), ('celebration', 'station')])

def build_string(lst_of_tups):
     final_str = ""
     for tup in list_of_tups:
          for item in tup:
               final_str = final_str + item[0]
     return final_str
     print build_string

****预期输出:hampcs ****

2 个答案:

答案 0 :(得分:0)

那些字符串操作函数容易出错:它们定义了很多变量,内部循环中可以return,有意想不到的副作用......

一旦您习惯于列出理解,您就可以轻松地创建这样的程序。具有很好的执行性能(字符串连接很慢)。一种方式:

def build_string(lst_of_tups):
   return "".join([x[0] for y in lst_of_tups for x in y])

基本上,在列表解析中只有2个循环(展平数据)从每个字符串中提取每个第一个字符,使用str.join连接在一起重建字符串。

答案 1 :(得分:0)

一旦在函数中找到return语句,该函数就会结束。这条线

print build_string

无法联系到。 (另一个问题是未定义名称build_string。)

使用您的功能:

result = build_string(lst_of_tups) # calls your function and puts the return value in the result variable
print result # print the result

当然,中间变量result不是必需的,您也可以发布print build_string(lst_of_tups)