python - 与各种列表合并

标签 python

我的任务是将这些列表合并为一个列表。例如:

all_lst = [[2, 7, 10], [0, 4, 6], [3, 11]]
>>> [0, 2, 3, 4, 6, 7, 10, 11]

我定义了:

 def merge(left, right):
     results = []
    while left and right:
        if left[0]< right[0]:
            results.append( left[0])
            left.remove( left[0])
        else:
            results.append( right[0])
            right.remove (right[0])
    results.extend(left)
    results.extend(right)
    return results

def merge_lists(all_lst):
    for i in range( len(all_lst)):
        A = merge(all_lst[i], all_lst[ i+1])
        new = all_lst[i+2:]
        B = merge( list(A), list(new))
    return B

但是 IDLE 给了我:

   Traceback (most recent call last):
  File "<pyshell#162>", line 1, in <module>
    print(merge_lists(all_lst))
  File "<pyshell#161>", line 5, in merge_lists
    B = merge( list(A), list(new))
  File "<pyshell#110>", line 4, in merge
    if left[0]< right[0]:
TypeError: unorderable types: int() < list()

如果您能告诉我出了什么问题,我将不胜感激。谢谢~!

最佳答案

不要试图重新发明威尔。使用 itertools 中的 chain ,像这样:

>>> import itertools as it
>>> i = [[2, 7, 10], [0, 4, 6], [3, 11]]
>>> sorted(it.chain(*i))
[0, 2, 3, 4, 6, 7, 10, 11]

需要排序调用,因为您的结果需要排序。

关于python - 与各种列表合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22496509/

相关文章:

python - 如何从一维Python中的polyfit中获取最小二乘/误差之和

python - ProgrammingError : (psycopg2. ProgrammingError) 无法适配类型 'dict'

Python 脚本 - mysql.connector 不更新 MariaDB 表

python - Tensorflow 不使用 GPU,发现 xla_gpu 不是 gpu

python - 无法写入文本文件

python - 使用Python 3删除数据框中多个指定列中具有空值的特定行

python - 子进程运行 scp 身份文件不可访问

Python:忽略 csv 文件中的特定行

java - 实现一个 java UDF 并从 pyspark 调用它

python - 尝试将文件写入 Excel 文档