[英]Write a function that merges two lists, alternating elements from both lists. Python code
For example if a = [1, 4, 9, 16] and b = [9, 7, 4, 9, 11], the function returns a new list, result = [1, 9, 4, 7, 9, 4, 16, 9, 11]例如如果 a = [1, 4, 9, 16] 和 b = [9, 7, 4, 9, 11],则 function 返回一个新列表,结果 = [1, 9, 4, 7, 9, 4 , 16, 9, 11]
This is the code I have so far.这是我到目前为止的代码。
def merge(a,b):
mergedList =[]
for i in range(len(a)):
mergedList.append(a[i])
mergedList.append(b[i])
def main():
a = [1,4,9,16]
b = [9,7,4,9,11]
print("List a is", a)
print("List b is", b)
result = merge(a,b)
print("The merged list is", result)
main()
The output I get is我得到的 output 是
List a is [1,4,9,16]
List b is [9,7,4,9,11]
The merged list is None
Does anyone know why the output for the new merged list is None?有谁知道为什么新合并列表的 output 是无?
You have not returned the merged list.您尚未返回合并列表。 Therefore it's value is None.因此它的值为无。 Change the first function to:将第一个 function 更改为:
def merge(a,b):
mergedList =[]
for i in range(len(a)):
mergedList.append(a[i])
mergedList.append(b[i])
return mergedlist
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.