Python——在列表中合併元組元素
在本文中,我們將學習如何合併列表中的元組元素。使用 join 和 map 方法是一件非常直接的事情。按照以下步驟完成任務。
- 用包含字串的元組初始化列表。
- 編寫一個名為 join_tuple_string 的函式,它將元組作為引數並返回一個字串。
- 使用 map(join_tuple_string, list) 方法合併列表中的元組。
- 將結果轉換為列表。
- 列印結果。
示例
# initializing the list with tuples string_tuples = [('A', 'B', 'C'), ('Tutorialspoint', 'is a', 'popular', 'site', 'for tech learnings')] # function that converts tuple to string def join_tuple_string(strings_tuple) -> str: return ' '.join(strings_tuple) # joining all the tuples result = map(join_tuple_string, string_tuples) # converting and printing the result print(list(result))
如果你執行以上程式碼,你將獲得以下結果。
輸出
['A B C', 'Tutorialspoint is a popular site for tech learnings']
結論
如果你對本文有任何疑問,請在評論區提問。
廣告