Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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 3.x 迭代二维列表并附加到多个其他列表_Python 3.x_List - Fatal编程技术网

Python 3.x 迭代二维列表并附加到多个其他列表

Python 3.x 迭代二维列表并附加到多个其他列表,python-3.x,list,Python 3.x,List,我有一个二维列表: lst = [[1,2,3,4,5,6,7,8,9],[11,12,13,14,15]] 我想将二维列表中每个列表的0到N-1存储在一个单独的列表中,将1到N存储在另一个列表中。因此,我创建了两个新列表,将其追加到与二维lst长度相同的位置: alpha, beta = [[]]*len(lst), [[]]*len(lst) 然后我运行以下代码: for i in range(len(lst)): for j in range(len(lst[i])-1):

我有一个二维列表:

lst = [[1,2,3,4,5,6,7,8,9],[11,12,13,14,15]]
我想将二维列表中每个列表的0到N-1存储在一个单独的列表中,将1到N存储在另一个列表中。因此,我创建了两个新列表,将其追加到与二维lst长度相同的位置:

alpha, beta = [[]]*len(lst), [[]]*len(lst)
然后我运行以下代码:

for i in range(len(lst)):
    for j in range(len(lst[i])-1):
        alpha[i].append(lst[i][j])
        beta[i].append(lst[i][j+1])
但是for循环似乎每次都在遍历所有列表

我想知道结果

alpha = [[1,2,3,4,5,6,7,8],[11,12,13,14]]
beta = [[2,3,4,5,6,7,8,9],[12,13,14,15]]
相反,我得到了

alpha = [[1,2,3,4,5,6,7,8,11,12,13,14],[1,2,3,4,5,6,7,8,11,12,13,14]]
beta = [[2,3,4,5,6,7,8,9,12,13,14,15],[2,3,4,5,6,7,8,9,12,13,14,15]]

我的代码肯定有问题,我无法解决,任何帮助都将不胜感激

我认为列表理解可能会使您的代码更加简洁:

foo, bar= [], []

for i in range(len(lst)):
    for j in range(len(lst[i])-1):
        foo.append(lst[i][j])
        bar.append(lst[i][j+1])
    alpha[i] = foo
    beta[i] = bar
    foo, bar = [], []
alpha = [i[:-1] for i in lst]
beta = [i[1:] for i in lst]

>>> alpha
[[1, 2, 3, 4, 5, 6, 7, 8], [11, 12, 13, 14]]
>>> beta
[[2, 3, 4, 5, 6, 7, 8, 9], [12, 13, 14, 15]]

感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。A通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有其他类似问题的读者更有用。请在您的回答中添加一些解释,包括您所做的假设。