Python - 将给定的数字附加到列表的每个元素
给定一个列表和一个数字,编写一个Python程序将数字附加到列表的每个元素上。
例子:
input = [1,2,3,4,5]
key = 5 (number to be appended)
output = [1,5,2,5,3,5,4,5,5,5]
以下是实现此功能的方法:
方法一:使用for循环
Python
input = [1, 2, 3, 4, 5]
key = 7
result = []
for ele in input:
result.append(ele)
result.append(key)
print(result)
Python
import itertools
input = [1, 2, 3, 4, 5]
key = 7
result = list(itertools.chain(*[[ele, key] for ele in input]))
print(result)
Python
input = [1, 2, 3, 4, 5]
key = 7
result = []
for x, y in zip(input, [key]*len(input)):
result.extend([x, y])
print(result)
输出:
[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]
方法 2:使用列表推导和itertools.chain
Python
import itertools
input = [1, 2, 3, 4, 5]
key = 7
result = list(itertools.chain(*[[ele, key] for ele in input]))
print(result)
输出:
[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]
方法 3:使用zip和for 循环
Python
input = [1, 2, 3, 4, 5]
key = 7
result = []
for x, y in zip(input, [key]*len(input)):
result.extend([x, y])
print(result)
输出:
[1, 7, 2, 7, 3, 7, 4, 7, 5, 7]