Python中文
首页
教程
问答
标签
搜索
登录
注册
如何在给定两个已排序列表的情况下创建已排序列表(不能修改任一给定列表)
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我的目标是创建一个函数,将两个排序的int列表作为参数 并创建已排序的合并列表。唯一的问题是我不被允许 修改两个原始列表(并且不能复制以修改其中一个)。只有range()、len()、index()、append()是允许的内置项。到目前为止,我被难住了。你知道吗</p> <p>以下是我所拥有的:</p> <pre><code>def merge_lists( list1, list2 ): sortedList = [] pointer1 = 0 pointer2 = 0 while pointer1 < len( list1 ) and pointer2 < len( list2 ): if list1[ pointer1 ] < list2[ pointer2 ]: sortedList.append( list1[ pointer1 ] ) pointer1 += 1 elif list2[ pointer2 ] < list1[ pointer1 ]: sortedList.append( list2[ pointer2 ] ) pointer2 += 1 elif list1[ pointer1 ] == list2[ pointer2 ]: sortedList.append( list1[ pointer1 ] ) sortedList.append( list2[ pointer2 ] ) pointer1 += 1 pointer2 += 1 if pointer1 == 0: for number in list1: sortedList.append( number ) if pointer2 == 0: for number in list2: sortedList.append( number ) else: amountNumbersLeft1 = len( list1 ) - ( pointer1 - 1 ) amountNumbersLeft2 = len( list2 ) - ( pointer2 - 1 ) if amountNumbersLeft1 != 0: for o in range( 1, ( amountNumbersLeft1 ) ): sortedList.append( list1[ o ] ) if amountNumbersLeft2 != 0: for i in range( 1, ( amountNumbersLeft2 ) ): sortedList.append( list2[ i ] ) return sortedList </code></pre> <p>我的测试用例以([1,2,3],[4,5,6])作为参数,返回一个列表[1,2,3,4,5,6]。但是,我的测试用例([2,13,19],[3,6,9,22])返回了[2,3,6,9,13,19,6]。你知道吗</p> <p>我觉得有一个更简单的排序解决方案。请帮忙。谢谢。你知道吗</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这很简单。使用+合并列表,然后使用排序函数。你知道吗</p> <pre><code>merged = sorted(list1 + list2) </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
当pandas中出现小数据时,DataFrame.resample()被调用时,内存不足
10 回答
当Pandas中存在许多条件时,如何过滤数据?
8 回答
当pandas中没有公共列名时,我们应该如何组合多个数据集而不在行或列中重复
1 回答
当pandas中的值为null时,不使用pandas的to_列表
2 回答
当Pandas中的值和条目匹配时,如何计算键的计数?
10 回答
当pandas列中有字符串时,如何从该列获取最长长度的string/integer/float
3 回答
当pandas列重命名创建列名重复时该怎么办
5 回答
当Pandas在带有颜色标签的多个子图中创建散点图时,无法设置xlabel
4 回答
当pandas导入openpyxl模块时,该模块没有属性''uuuversion''
7 回答
当pandas数据在python中聚合时,如何计算每组尾部的sum | mean |中值
6 回答
当Pandas数据头以列(如xls)拆分时,如何读取Pandas数据头
5 回答
当Pandas数据帧包含nan时,用“新信息”更新Pandas数据帧
7 回答
当pandas是imp时,Cx\u freeze TypeError只能使用numpy依赖项将list(而不是“NoneType”)连接到list
5 回答
当Pandas满足一定条件时,如何放弃整个群体
4 回答
当Pandas的时间增量指数不规则时,如何获得时间序列值的日差?
9 回答
当Pandas通过read\u csv方法读取大文件时。IOError:[Errno 13]权限被拒绝
6 回答
当panda列有空值时,如何将其转换为int?
7 回答
当param=''时使用Beautiful Soup访问属性的参数
9 回答
当paramiko抛出“无现有会话”异常时,标准输入流挂起
10 回答
当parentchild在同一端口上监听时会发生什么?
10 回答