简体   繁体   English

编写一个 function 合并两个列表,交替两个列表中的元素。 Python代码

[英]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.

相关问题 处理python列表。 (访问特定元素) - Manipulating python lists. (accessing specific elements) 我有两个清单。 我想从其中一个列表中给出的元素中选出第三个 - I have two lists. I would like to make a third from the elements given in one of the lists 如何将可迭代对象拆分为两个具有交替元素的列表 - How to split an iterable into two lists with alternating elements 产生两个列表的交替值的生成器 function - Generator function that yields alternating values of two lists 合并两个排序列表。 对python中“=”运算符的工作感到困惑 - Merge Two Sorted Lists. confused about working of "=" operator in python 两个列表上的 Python Itertools。 从每个列表中获取超过 1 个值 - Python Itertools on two lists. Get more then 1 value from each list 写一个最长的 function,它也需要一个列表 ll 的列表。 它应该返回(引用) ll 中最长的列表 - Write a function longest, which also takes a list ll of lists. It should return (a reference to) the longest of the lists in ll 列表列表中的元素相等。 删除一个 - Equal elements in list of lists. Delete one 创建列表列表。 修改列表中的元素 - Create a list of lists. Modify elements in the list 比较列表。 哪些元素不在列表中? - Comparing lists. Which elements are NOT in a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM