如何从Python的列表中提取每个位置的数字

2 投票
5 回答
870 浏览
提问于 2025-04-18 01:38

我有一个列表:

N=[[0,3,4], [0,1,2,9,3], [0,3]]

我该怎么做才能用这个列表生成另一个列表,让新列表中的每个项目都是原列表中对应位置的数字,这样新列表看起来像:

newList=[[0,0,0], [3,1,3],  [4,2] ,[9], [3]]

新列表中的第一个项目是一个子列表,里面包含了N[0]中的第一个数字、N[1]中的第一个数字和N[2]中的第一个数字。接下来的子列表会对N中的第二个位置做同样的事情。

5 个回答

0

这里有一个解决方案,它不使用列表推导式,也不需要提前处理来确定列表的最大长度。

N = [[0,3,4], [0,1,2,9,3], [0,3]]
newList = []

progress = True
i = 0;

while (progress):
    progress = False
    sublist = []

    for list in N:
        if len(list) <= i:
            continue
        else:
            sublist.append(list[i])
            progress = True

    if not progress:
        break

    newList.append(sublist)
    i = i+1

print(N)
print(newList)
0

下面这个怎么样:

# original list
N = [[0,3,4], [0,1,2,9,3], [0,3]]

# create a new list of `n` lists (n being the length of the longest sublist in N)
newList = [[] for i in xrange(max([len(l) for l in N]))]

# iterate over each list
# enumerate - use the index to append into correct target list
for l in N:
    for i, val in enumerate(l):
        newList[i].append(val)

print newList

输出结果是:

[[0, 0, 0], [3, 1, 3], [4, 2], [9], [3]]

希望这对你有帮助!:)

0

这里有一种奇怪且效率不高的方法(但可能比较容易理解):

  • 先找出列表中最长的长度。
  • 然后从0开始,遍历所有这些列表,直到那个最大长度。
  • 如果出现错误,那说明你最初的列表(也就是来自N的那个列表)没有这个项目。

N=[[0,3,4], [0,1,2,9,3], [0,3]]
newList = []

max_items = max([len(lst) for lst in N])
for n_lst in N:
    for i in range(max_items):
        if len(newList) <= i:
            newList.append([])
        try:
            newList[i].append(n_lst[i])
        except IndexError:
            pass

print "new List: %s" % newList     

另一种方法,可能会让代码更简洁,就是把newList初始化为一个包含5个项目的列表,因为你在矩阵N中最长的列表([0,1,2,9,3])有5个元素。这样你就知道你的结果(newList变量)会有5个列表:

N=[[0,3,4], [0,1,2,9,3], [0,3]]
newList = []

max_items = max([len(lst) for lst in N])
newList=list([] for _ in range(max_items))

for i in range(max_items):
    for n_lst in N:
        if len(n_lst) > i:
          newList[i].append(n_lst[i])
print "new List: %s" % newList

注意,除了捕获IndexException错误外,你也可以检查你正在评估的列表的长度len()是否大于i

编辑:

刚看到John Clements的回复(https://stackoverflow.com/a/22901233/289011),这个方法明显更简洁。

1

试试列表推导式

newList= [reduce(lambda x,y: x + [y[i]] if i<len(y) else x, N, [])
          for i in range(max(map(len,N)))]

这里的 for 是用来遍历 N 中最长子列表的长度,使用 maplen 来创建一个临时列表,这个列表里存的是 N 中每个列表的长度,以便计算出最长的长度。

reduce 则是通过从每个输入子列表中提取第 i 个元素来构建结果中的每个子列表——但前提是这个子列表的长度足够。

4

可以使用 izip_longest,然后把默认值过滤掉,比如:

from itertools import izip_longest

N=[[0,3,4], [0,1,2,9,3], [0,3]]   
new_list = [[el for el in items if el is not None] for items in izip_longest(*N)]
# [[0, 0, 0], [3, 1, 3], [4, 2], [9], [3]]

撰写回答