按字母顺序创建新列表

时间:2015-03-17 19:06:33

标签: python list

我的python说明是:编写一个名为merge的函数 采用两个字符串列表,每个字符串按字母顺序排列。 该函数应返回包含所有字符串的列表 按字母顺序排列。 该函数应返回一个列表,其中包含按字母顺序排列的所有字符串 顺序。
例如,如果函数被赋予了两个列表

[“cat”, “dog”, “pat”][ “bat”, “hamster”, “piglet”, “worm”]

它应该返回列表

[“bat”, “cat”, “dog “, hamster”, “pat”, “piglet”, “worm”].

粗略地说,您将从一个空列表开始,以保​​存合并列表 并在每个列表的开头设置为0的索引。 比较第一个单词。以字母顺序排在第一位 order被附加到合并列表和该列表的索引 增加了。继续,直到其中一个列表为空并复制 另一个列表的其余部分到合并列表。

现在我有代码

list1 = ["cat", "dog", "pat"]
list2 = [ "bat", "hamster", "piglet", "worm"]

def merge (list1, list2):
    newlist = []
    newlist = list1 +list2
    final = sorted(newlist)
    return final
print merge (list1, list2)

它有效,但它不遵循指示。我不确定如何比较两个列表然后将它们附加到新列表。如果索引设置为0,我也没做过。任何人都可以帮助调整我的代码,使其符合说明吗?

4 个答案:

答案 0 :(得分:2)

让我们从编写比较函数开始

def cmp_lists(L1,L2):
    '''returns the first item of the lesser list and the remaining lists'''
    if L1 < L2:
       return L1[0],(L1[1:],L2)
    return L2[0],(L1,L2[1:])

现在写一个合并2个列表的方法

def merge(L1,L2):
    if not L1: #if L1 is empty return L2
       return L2
    elif not L2: #if L2 is empty return L1
       return L1
    #otherwise take the first item from one of the lists
    next_itm,(L1,L2) = cmp_lists(L1,L2)
    # and recursively carry on
    return [next_itm] + merge(L1,L2)

答案 1 :(得分:0)

您被指示的是为merge排序算法中常用的简单merge-sort函数编写实现。

由于两个列表都已排序,因此您无需再次加入和排序。相反,只需循环直到其中一个列表为空并继续比较两个列表的第一个元素。弹出较短的元素并添加到较新的列表中。

继续这样做,直到其中一个或两个列表变空。如果其中一个列表中剩余了额外的元素,请将它们全部添加到新列表中。

我建议您再次编写代码。

答案 2 :(得分:0)

通过查看列表的顶部元素并将它们放入新创建的列表中,合并排序。

def merge(list1, list2): # assume input lists are sorted
    iter1 = iter(list1) # iterator on the list
    iter2 = iter(list2)
    top1 = iter1.next() # first element of the list
    top2 = iter2.next()
    newlist = [] # new list to fill in
    while True: # loop will exit with break statement
        if top1 <= top2: 
            newlist.append(top1) # put smaller element in new list 
            try:
                top1 = iter1.next() # try to get next element in list1
            except StopIteration:
                newlist.append(top2) # if not, fill list with top2
                newlist.extend(list(iter2)) # and rest of list2
                break # and exit loop
        else:
            newlist.append(top2)
            try:
                top2 = iter2.next()
            except StopIteration:
                newlist.append(top1) # if not, fill list with top1
                newlist.extend(list(iter1)) # and rest of list1
                break
    return newlist

答案 3 :(得分:0)

这是合并排序?哦,这并不难。只需反转两个列表,比较每一对,然后弹出失败者。一旦任何一个列表为空,剩下的列表将按照整个结果的升序排序,因此只需将其连接即可。

from operator import itemgetter as iget

def merge(lst1, lst2):
    lst1, lst2 = lst1[::-1], lst2[::-1]
    # popping from the end is MASSIVELY better than popping from the front
    result = []
    while True:
        if not all([lst1, lst2]): # one list is empty:
            return result + lst1[::-1] + lst2[::-1] # so add them both and return
        lst_to_pop_from = min(lst1,lst2, key=iget(-1))
        # gets the list with the smallest final element
        result.append(lst_to_pop_from.pop())

# DEMO

In [53]: list1 = ["cat", "dog", "pat"]

In [54]: list2 = [ "bat", "hamster", "piglet", "worm"]

In [55]: merge(list1, list2)
Out[55]: ['bat', 'cat', 'dog', 'hamster', 'pat', 'piglet', 'worm']