python新手…我试着写一个函数merge()
来取两个列表并组合它们,然后我想将其扩展到n
个数的列表。
我从这段代码中得到的输出只是grapes
列表,而不是与apples
列表连接。
使用我的函数失败:
grapes = ['purple', 'red']
apples = ['green', 'yellow', 'orange']
def merge():
''' merge the lists '''
for i in apples:
grapes.append(i)
print("Concatenated list: " + str(grapes))
merge()
输出:
Concatenated list: ['purple', 'red']
感谢您的阅读…
在输出葡萄之前应该先调用merge()
我的意思是:
grapes = ['purple', 'red']
apples = ['green', 'yellow', 'orange']
def merge():
''' merge the lists '''
for i in apples:
grapes.append(i)
merge()
print("Concatenated list: " + str(grapes))
或者你可以直接写:
fruits = grapes + apples
print(fruits)
使用
array1 = ["a" , "b" , "c" , "d"]
array = [1 , 2 , 3 , 4 , 5]
def merge(*array_list):
output_array = []
for array in array_list:
output_array = output_array + array
return output_array
merged_array = merge(array1 , array2)
希望能有所帮助:)