【问题标题】:Merge two lists in python to one将python中的两个列表合并为一个
【发布时间】:2015-10-29 19:56:55
【问题描述】:

我需要将两个列表合并到一个列表中并打印出来

例如:

list1 = [9, 3, 5, 7]
list2 = [5, 4 , 6]

list3 = [9, 5, 3, 4, 5, 6, 7]

我需要用“for”或“while”来做,因为我们还没有学到比这更高级的东西。

我现在的代码:

list1 = [3, 4, 5, 6]
list2 = [1, 2, 0, 9, 9]
tlist = []
n1 = len(list1)
n2 = len(list2)
n3 = n1 + n2
n4 = len(list2) - 1
n5 = len(list1) - 1
i = 1
c = 0
while i in range(0, n3):
    tlist.insert(i, list1[c])
    tlist.insert(i, list2[c])    
    c += 1
    i += 2
tlist.extend(list2[n4:])
tlist.extend(list1[n5:])
for num in tlist:
    print num

结果是:

3
1
4
2
5
0
6
9
9
6

(最后应该是这样的) 所以如果 len(list1) = len(list2) 我已经设法做到了 但如果列表的长度不同,它就不起作用

【问题讨论】:

  • 要么你应该先写一个列表然后另一个,或者在你的循环中检查是否有任何列表已经用尽
  • 您只需要任何合并,还是需要维护您正在使用的交错?

标签: python python-2.7 python-3.x


【解决方案1】:

无论列表长度如何,您的代码始终会附加每个列表的最后一个元素。相反,试试这个扩展:

tlist.extend(list2[c+1:])
tlist.extend(list1[c+1:])

通过此更改,我得到了预期的输出:它从循环停止的地方 (c) 开始,而不是从最后一个元素 (n4, n5) 开始。

另外,你的 while 循环绑定是错误的;它仅在两个列表长度相差不超过 1 时才有效。否则,您将收到下标超出范围错误。试试这个:

for c in range(min(n1, n2)):
    tlist.insert(i, list1[c])
    tlist.insert(i, list2[c])
    i += 2
    # do not increment c; the for statement handles that part.

当任一列表用完时,这将退出复制。

顺便说一下,改成有意义的变量名。 n1-n5 系列没有告诉我们它们的用途。 'c' 和 'i' 也很弱。不要害怕输入更多内容。


更新程序,包括加长测试用例:

list1 = [3, 4, 5, 6]
list2 = [1, 2, 0, 9, 8, 7, -1]
tlist = []
n1 = len(list1)
n2 = len(list2)
n4 = len(list2) - 1
n5 = len(list1) - 1
i = 1

for c in range(min(n1, n2)):
    tlist.insert(i, list1[c])
    tlist.insert(i, list2[c])
    i += 2
    print tlist

tlist.extend(list2[c+1:])
tlist.extend(list1[c+1:])

print tlist

【讨论】:

  • 好的,我试过了,但是当我向列表之一添加更多数字时,我仍然遇到索引错误。以及当我完成代码时的变量
  • 好的......所以发布程序的当前状态和你得到的结果?您在原始帖子中做得很好,但您必须保持下去。为了加快速度,我将添加我认为该程序现在应该是的内容。
  • 谢谢你,我试过你的代码,它正是我需要的,但你能解释一下你所做的循环吗?
  • (1) 你在你的代码中遗漏了什么,它不起作用(学习经验)? (2)我不想过多解释:你在查找 Python 的 forminrange 时有什么不明白的地方?
  • 我认为循环构建得不好,这是我第一次使用循环,我花了一段时间来了解如何正确使用它。我不明白范围(最小部分。当我尝试放置各种其他范围时,当循环长度不同时它仍然不起作用。
【解决方案2】:

只需使用“+”添加两个列表即可合并它们。

In [1]: a = [1,2,3]

In [2]: b = [2,3]

In [3]: a+b
Out[3]: [1, 2, 3, 2, 3]

或者您可以执行以下操作:

for i in b:
   ...:     a.append(i)
   ...:     

In [5]: a
Out[5]: [1, 2, 3, 2, 3]

【讨论】:

  • 如果你看我的例子,新的列表需要是:list3 = [list1[0], list2[0], list1[1], list2[1]...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 2014-01-03
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多