Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.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_Insert - Fatal编程技术网

如何在多个Python列表的元素之间插入元素?

如何在多个Python列表的元素之间插入元素?,python,list,insert,Python,List,Insert,假设我有多个Python列表。在多个Python列表的元素之间插入元素的一种快速方法是什么 # Have list1 = [1, 2, 3] list2 = [10, 11, 12] list3 = [20, 21, 22] # Expect list_between = [1, 10, 20, 2, 11, 21, 3, 12, 22] list_between=[i代表列表ZipList1中的l,列表2,列表3代表列表中的i] 只需使用zip并使用列表理解在元组列表中按顺序打印元素 li

假设我有多个Python列表。在多个Python列表的元素之间插入元素的一种快速方法是什么

# Have
list1 = [1, 2, 3]
list2 = [10, 11, 12]
list3 = [20, 21, 22]

# Expect
list_between = [1, 10, 20, 2, 11, 21, 3, 12, 22]
list_between=[i代表列表ZipList1中的l,列表2,列表3代表列表中的i] 只需使用zip并使用列表理解在元组列表中按顺序打印元素

list(zip(list1, list2, list3)) # returns [(1, 10, 20), (2, 11, 21), (3, 12, 22)]
list_between=[i代表列表ZipList1中的l,列表2,列表3代表列表中的i] 只需使用zip并使用列表理解在元组列表中按顺序打印元素

list(zip(list1, list2, list3)) # returns [(1, 10, 20), (2, 11, 21), (3, 12, 22)]

我不知道有什么简单/快速的方法,但如果这个示例具有代表性,您希望基本上以这种方式从多个列表中构建列表,您可以执行以下操作:

n = 3 # length of our lists, must all be the same for simple logic
our_lists = [list1, list2, list3]
new_list = []
for i in range(3):
    for l in our_lists:
        new_list.append(l[i])

我不知道有什么简单/快速的方法,但如果这个示例具有代表性,您希望基本上以这种方式从多个列表中构建列表,您可以执行以下操作:

n = 3 # length of our lists, must all be the same for simple logic
our_lists = [list1, list2, list3]
new_list = []
for i in range(3):
    for l in our_lists:
        new_list.append(l[i])

如果所有列表具有相同数量的元素,则可以在列表中使用zip:

list_between = [ e for e3 in zip(list1,list2,list3) for e in e3 ]

如果所有列表具有相同数量的元素,则可以在列表中使用zip:

list_between = [ e for e3 in zip(list1,list2,list3) for e in e3 ]
用于任意插入的纯python解决方案 如果要将listB中的元素插入listA中的任意位置,可以使用list.insertindex、object\u to\u insert方法

如果您非常关心速度,您应该知道这可能不会很快,因为python列表是,而不是链表。为了更快地插入,您可能需要实现自己的链表类型

替代numpy解决方案 如果您想以示例所示的方式组合三个列表,可以将它们插入numpy数组并进行数组的转置

在[1]中:将numpy作为np导入 在[2]中:listA=[1,2,3] …:listB=[4,5,6] …:listC=[7,8,9] ...: …:arr=np.array[listA,listB,listC] …:啊 出[2]: 数组[[1,4,7], [2, 5, 8], [3, 6, 9]] 在[3]中:arr.T.展平 Out[3]:数组[1,4,7,2,5,8,3,6,9] 在[4]中:arr.T.flatte.tolist Out[4]:[1,4,7,2,5,8,3,6,9] 用于任意插入的纯python解决方案 如果要将listB中的元素插入listA中的任意位置,可以使用list.insertindex、object\u to\u insert方法

如果您非常关心速度,您应该知道这可能不会很快,因为python列表是,而不是链表。为了更快地插入,您可能需要实现自己的链表类型

替代numpy解决方案 如果您想以示例所示的方式组合三个列表,可以将它们插入numpy数组并进行数组的转置

在[1]中:将numpy作为np导入 在[2]中:listA=[1,2,3] …:listB=[4,5,6] …:listC=[7,8,9] ...: …:arr=np.array[listA,listB,listC] …:啊 出[2]: 数组[[1,4,7], [2, 5, 8], [3, 6, 9]] 在[3]中:arr.T.展平 Out[3]:数组[1,4,7,2,5,8,3,6,9] 在[4]中:arr.T.flatte.tolist Out[4]:[1,4,7,2,5,8,3,6,9] 您可以使用:

进口itertools listitertools.chain.from_iterableziplist1、list2、list3 如果列表的长度不相同,则所有列表都将缩小为最短列表的长度。

您可以使用:

进口itertools listitertools.chain.from_iterableziplist1、list2、list3 如果列表的长度不相同,则所有列表都将缩小为最短列表的长度。

中有循环,它可以执行您想要的操作:

from itertools import cycle, islice
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

list1 = [1, 2, 3]
list2 = [10, 11, 12]
list3 = [20, 21, 22]

list_between = list(roundrobin(list1,list2,list3))
print(list_between)
输出:

[1, 10, 20, 2, 11, 21, 3, 12, 22]
请注意,它也适用于不同长度的参数。请参见docstring。

中有循环,它可以执行您想要的操作:

from itertools import cycle, islice
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

list1 = [1, 2, 3]
list2 = [10, 11, 12]
list3 = [20, 21, 22]

list_between = list(roundrobin(list1,list2,list3))
print(list_between)
输出:

[1, 10, 20, 2, 11, 21, 3, 12, 22]

请注意,它也适用于不同长度的参数,请参见docstring。

这里是一种很有技巧的方法,但与使用np.transpose相比,速度较慢。这是通过使用slice在元素之间插入0,然后将列表添加到一起实现的:

# e.g.
# arr1 = [1, 0, 0, 2, 0, 0, 3, 0, 0]
# arr2 = [0, 1, 0, 0, 2, 0, 0, 3, 0]
# arr3 = [0, 0, 1, 0, 0, 2, 0, 0, 3]
#
# arr_ = [1, 1, 1, 2, 2, 2, 3, 3, 3] # use np.add to fast insert
 
list1 = np.insert(list1, slice(1, None, 1), 0) # create 0,0 paddings in between
list1 = np.insert(list1, slice(1, None, 2), 0)
list1 = np.insert(list1, 0, [0]*(0))
list1 = list1.tolist()
list1.extend([0]*(3-1))

list2 = np.insert(list2, slice(1, None, 1), 0)
list2 = np.insert(list2, slice(1, None, 2), 0)
list2 = np.insert(list2, 0, [0]*(0+1))
list2 = list2.tolist()
list2.extend([0]*(3-2))

list3 = np.insert(list3, slice(1, None, 1), 0)
list3 = np.insert(list3, slice(1, None, 2), 0)
list3 = np.insert(list3, 0, [0]*(0+2))
list3 = list3.tolist()
list3.extend([0]*(3-3))

list_ = np.add(list1, list2)
list_ = np.add(list_, list3)

list_
array([ 1, 10, 20,  2, 11, 21,  3, 12, 22])

这是一种很有技巧的方法,但与使用np.transpose相比速度较慢。这是通过使用slice在元素之间插入0,然后将列表添加到一起实现的:

# e.g.
# arr1 = [1, 0, 0, 2, 0, 0, 3, 0, 0]
# arr2 = [0, 1, 0, 0, 2, 0, 0, 3, 0]
# arr3 = [0, 0, 1, 0, 0, 2, 0, 0, 3]
#
# arr_ = [1, 1, 1, 2, 2, 2, 3, 3, 3] # use np.add to fast insert
 
list1 = np.insert(list1, slice(1, None, 1), 0) # create 0,0 paddings in between
list1 = np.insert(list1, slice(1, None, 2), 0)
list1 = np.insert(list1, 0, [0]*(0))
list1 = list1.tolist()
list1.extend([0]*(3-1))

list2 = np.insert(list2, slice(1, None, 1), 0)
list2 = np.insert(list2, slice(1, None, 2), 0)
list2 = np.insert(list2, 0, [0]*(0+1))
list2 = list2.tolist()
list2.extend([0]*(3-2))

list3 = np.insert(list3, slice(1, None, 1), 0)
list3 = np.insert(list3, slice(1, None, 2), 0)
list3 = np.insert(list3, 0, [0]*(0+2))
list3 = list3.tolist()
list3.extend([0]*(3-3))

list_ = np.add(list1, list2)
list_ = np.add(list_, list3)

list_
array([ 1, 10, 20,  2, 11, 21,  3, 12, 22])

注意:这只适用于数字。反馈非常感谢注意:这只适用于数字。反馈非常感谢@Emerson Harkin非常有帮助我不知道你能做到。那么你如何组合转置矩阵呢?很高兴能帮助@YiXiangChong!我在numpy解决方案中添加了更多细节,以展示如何将其转化为列表。哇@Emerson Harkin这是一个非常出色的解决方案。谢谢分享。np.transpose是否适用于大型数据集或矩阵?我不太清楚numpy转置是如何工作的,但从理论上讲,对大型矩阵进行转置应该是相当昂贵的….?谢谢@Emerson Harkin非常有用,我不知道你能做到这一点。那么你如何组合转置矩阵呢?很高兴能帮助@YiXiangChong!我在numpy解决方案中添加了更多细节,以展示如何将其转化为列表。哇@Emerson Harkin这是一个非常出色的解决方案。谢谢分享。np.transpose是否适用于大型数据集或矩阵?
我不太清楚numpy转置是如何工作的,但理论上,对大型矩阵进行转置应该是相当昂贵的….?嗨@Daweo,谢谢分享。我是一个编程新手,对我来说太难理解了。你介意解释一下代码吗?@YiXiangChong:我担心我做不清楚,我建议先找python迭代器教程,然后再找itertools模块文档。你好@Daweo谢谢分享。我是编程新手,对我来说太难理解了。你介意解释一下代码吗?@YiXiangChong:我担心我做不清楚,我建议先找python迭代器教程,然后再找itertools模块文档。