将一个新列表与两个基本列表合并 [复制]

combining a new list with two base lists [duplicate]

提问人:Renan Andrade 提问时间:11/12/2023 最后编辑:Renan Andrade 更新时间:11/12/2023 访问量:125

问:

这个问题在这里已经有答案了:
8天前关闭。

社群在 8 天前审查了是否重新打开这个问题,并将其关闭:

原始关闭原因未解决

我想通过以下方式组合两个列表,即第一个元素的第一个元素是新列表的第一个元素,第二个元素的第一个元素是新列表的第二个元素,依此类推

count = 12
list = list(range(count))

list1 = []
list2 = []

for x in range(0, count, 4):
    list1.append(x)

for y in range(3, count, 4):
    list2.append(y)

#Concatenate doesn't work
newlist = list1 + list2

print(newlist)
print(list)

其结果是:

newlist = [0, 4, 8, 3, 7, 11]

但我想要这样的东西:

newlist = [0, 3, 4, 7, 8, 11]
python-3.x 列表 编号

评论


答:

-3赞 XM01 - stands with Palestine 11/12/2023 #1

你可以用它来存档你的结果sorted

count = 12
list = list(range(count))

list1 = []
list2 = []

for x in range(0, count, 4):
    list1.append(x)

for y in range(3, count, 4):
    list2.append(y)

print(list1)# ==> [0, 4, 8]
print(list2)# ==> [3, 7, 11]
newlist = list1 + list2
print(sorted(newlist))# ==> [0, 3, 4, 7, 8, 11]

评论

2赞 Chris 11/12/2023
这假设应该对值进行排序。这恰好是 OP 显示的示例,但它通常不起作用。
0赞 XM01 - stands with Palestine 11/12/2023
@Chris 提问者想要得到这个结果,这就是提问者想要的[0, 3, 4, 7, 8, 11]
1赞 Chris 11/12/2023
显然,这就是 OP 想要的,基于 ✓。不过,这不是他们所要求的。它恰好在列表已经排序并且每个列表中的值已经交错的情况下起作用。
1赞 gog 11/12/2023 #2

考虑:

a = [1,2,3]
b = [7,8,9]

c = [None] * (len(a) + len(b))
c[0::2] = a
c[1::2] = b
print(c)
## [1, 7, 2, 8, 3, 9]

顺便说一句,这被称为“交错”,请在论坛上搜索其他选项。

评论

0赞 Chris 11/12/2023
OP,请参阅 Python 中的切片如何用于 , 符号的背景c[0::2]c[1::2]
-1赞 Chris 11/12/2023 #3

将列表压缩在一起,然后用itertools.chain.from_iterable将它们拼合起来:

import itertools

l1 = [1, 2, 3]
l2 = [4, 5, 6]

list(itertools.chain.from_iterable(zip(l1, l2)))
# => [1, 4, 2, 5, 3, 6]

这之所以有效,是因为给出了对的列表:zip

list(zip(l1, l2))
# => [(1, 4), (2, 5), (3, 6)]

并将它们压平itertools.chain.from_iterable

这也适用于两个以上的列表:

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]

list(itertools.chain.from_iterable(zip(l1, l2, l3)))
# => [1, 4, 7, 2, 5, 8, 3, 6, 9]
1赞 FJSevilla 11/12/2023 #4

如果两个列表具有相同数量的项目,则只需使用 和 列表压缩:zip

count = 12

list1 = list(range(0, count, 4))
list2 = list(range(3, count, 4))

newlist = [item for pair in zip(list1, list2) for item in pair]
#[0, 3, 4, 7, 8, 11]

其中,使用“传统”表示周期和 ,将等价于:list.append

newlist = []
for pair in zip(list1, list2):
    for item in pair:
        newlist.append(item)