Python|在列表中加入一对元素的方法
给定一个列表,任务是连接列表中的一对元素。下面给出了一些解决给定任务的方法。
方法#1:使用zip()
方法
# Python code to demonstrate
# how to join pair of elements of list
# Initialising list
ini_list = ['a', 'b', 'c', 'd', 'e', 'f']
# Printing initial list
print ("Initial list", str(ini_list))
# Pairing the elements of lists
res = [i + j for i, j in zip(ini_list[::2], ini_list[1::2])]
# Printing final result
print ("Result", str(res))
输出:
Initial list ['a', 'b', 'c', 'd', 'e', 'f']
Result ['ab', 'cd', 'ef']
方法 #2:使用列表推导和 next 和 iters
# Python code to demonstrate
# how to join pair of elements of list
# Initialising list
ini_list = iter(['a', 'b', 'c', 'd', 'e', 'f'])
# Pairing the elements of lists
res = [h + next(ini_list, '') for h in ini_list]
# Printing final result
print ("Result", str(res))
输出:
Result ['ab', 'cd', 'ef']
方法#3:使用列表推导
# Python code to demonstrate
# how to join pair of elements of list
# Initialising list
ini_list = ['a', 'b', 'c', 'd', 'e', 'f']
# Printing initial lists
print ("Initial list", str(ini_list))
# Pairing the elements of lists
res = [ini_list[i] + ini_list[i + 1]
for i in range(0, len(ini_list), 2)]
# Printing final result
print ("Result", str(res))
输出:
Initial list ['a', 'b', 'c', 'd', 'e', 'f']
Result ['ab', 'cd', 'ef']