Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按字母顺序制作新列表_Python_List - Fatal编程技术网

Python 按字母顺序制作新列表

Python 按字母顺序制作新列表,python,list,Python,List,我的python指令是:编写一个名为merge 获取两个按字母顺序排列的字符串列表。 函数应该返回一个包含所有字符串的列表 按字母顺序。 函数应该返回一个列表,其中所有字符串都按字母顺序排列 订单。 例如,如果函数有两个列表 [“猫”、“狗”、“帕特”]和[“蝙蝠”、“仓鼠”、“小猪”、“蠕虫”] 它应该返回列表 [“bat”, “cat”, “dog “, hamster”, “pat”, “piglet”, “worm”]. 粗略地说,您将从一个空列表开始保存合并列表 并且在每个列表的开头

我的python指令是:编写一个名为
merge
获取两个按字母顺序排列的字符串列表。 函数应该返回一个包含所有字符串的列表 按字母顺序。 函数应该返回一个列表,其中所有字符串都按字母顺序排列 订单。
例如,如果函数有两个列表

[“猫”、“狗”、“帕特”]
[“蝙蝠”、“仓鼠”、“小猪”、“蠕虫”]

它应该返回列表

[“bat”, “cat”, “dog “, hamster”, “pat”, “piglet”, “worm”].
粗略地说,您将从一个空列表开始保存合并列表 并且在每个列表的开头将索引设置为0。 比较第一个单词。按字母顺序以先到者为准 顺序被追加到合并列表和该列表的索引中 增加了。继续,直到其中一个列表为空并复制 将其他列表的其余部分添加到合并列表中

现在我有密码了

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。有人能帮我调整代码,使其符合说明吗?

您得到的指示是为一个简单的
合并
函数编写一个实现,该函数在
合并排序
排序算法中广泛使用

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

继续这样做,直到一个或两个列表变为空。如果其中一个列表还有额外的元素,请将所有元素添加到新列表中


我鼓励您再次编写代码。

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

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:])

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

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
def merge(列表1、列表2):#假设输入列表已排序
iter1=iter(列表1)#列表上的迭代器
iter2=iter(列表2)
top1=iter1.next()#列表的第一个元素
top2=iter2.next()
newlist=[]#要填写的新列表
如果为True:#循环将以break语句退出

如果top1是合并排序?哦,这并不难。只需颠倒两个列表,比较每一对,然后弹出输家。一旦其中一个列表为空,剩余的列表将按照与整个结果相比的升序排序,因此只需将其连接起来即可

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())


如果只需要按字母顺序排列
final
,只需使用
final.sort()
。你的问题不是很清楚。@MikeVaughan不是很清楚吗?当然是!他清楚地提到他需要添加两个列表,然后对其应用合并排序。我们在这里帮助完成家庭作业吗?认真地问,而不是故意刁难。我想那部分似乎。。。关对我来说是比较第一个单词。按照字母顺序排在第一位的将被添加到合并列表中,并且该列表的索引将增加。
如果您只想按字母顺序排列两个列表中的所有内容,为什么需要这样做?@Dogweather我认为我们帮助完成家庭作业的方式与其他问题相同。如果这是一个很好的问题,并且展示了研究成果等等,那很好。若海报上写着“为我做家庭作业”,那个么答案是否定的。我在递归解决方案方面总是有问题。乔兰,干得好!
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']