Python 如何合并序列中的元素
Python序列包括字符串、列表、元组等。我们可以使用不同的方式合并Python序列的元素。
合并Python列表中的元素
示例
使用join()方法合并元素-
# List
myList = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U']
# Display the List
print ("List = " + str(myList))
# Merge items using join()
myList[0 : 3] = [''.join(myList[0 : 3])]
# Displaying the Result
print ("Result = " + str(myList))
输出
List = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U']
Result = ['HOW', 'A', 'R', 'E', 'Y', 'O', 'U']
使用Lambda合并Python列表中的元素
要使用Lambda合并元素,我们将使用reduce()方法。reduce()是Python中functools模块的一部分。让我们先了解如何安装和使用functools模块。
安装functools模块。
pip install functools
使用functools模块。
import functools
示例
以下是代码。
import functools
# List
myList = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U']
# Display the List
print("List = " + str(myList))
# Merge items using Lambda
myList[0: 3] = [functools.reduce(lambda i, j: i + j, myList[0: 3])]
# Displaying the Result
print("Result = " + str(myList))
输出
List = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U']
Result = ['HOW', 'A', 'R', 'E', 'Y', 'O', 'U']
使用for循环合并Python列表中的元素
示例
在这个示例中,我们将使用for循环来合并元素。
# List
myList = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82']
# Display the List
print("List = " + str(myList))
# Merge items
myList = [myList[i] + " " + myList[i+1] for i in range(0, len(myList), 2)]
# Displaying the Result
print("Result = " + str(myList))
输出
List = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82']
Result = ['john 96', 'tom 90', 'steve 86', 'mark 82']
使用切片和zip()方法合并Python列表中的元素
示例
在这个示例中,我们将使用zip()方法合并元素。
# List
myList = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82']
# Display the List
print("List = " + str(myList))
# Merge items with slice and zip()
myList = [':'.join(item) for item in zip(myList[::2],myList[1::2])]
# Displaying the Result
print("Result = " + str(myList))
输出
List = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82']
Result = ['john:96', 'tom:90', 'steve:86', 'mark:82']