使用嵌套列表制作列表列表的pythonic方式

时间:2020-08-13 10:12:09

标签: python list

我有一个嵌套列表

mylist = [['a', 'b', 'c', ['d', 'e', 'f'], 'g', 'h', ['i', 'j', 'k']]]

有什么方法可以使用python获得类似结果

mylist = [['a', 'b', 'c', 'd', 'g', 'h', 'i'],
          ['a', 'b', 'c', 'e', 'g', 'h', 'j'],
          ['a', 'b', 'c', 'f', 'g', 'h', 'k']]

2 个答案:

答案 0 :(得分:0)

l = [
      [
        'a', 
        'b', 
        'c', 
        ['d', 'e', 'f'], 
        'g', 'h', 
        ['i', 'j', 'k']
      ]
    ]
l = l[0]
final = []
count = 0

while count <= 2:
    result = []
    for i in l:
        if not isinstance(i, list):
            result.append(i)
        else:
            result.append(i[count])
    count += 1
    final.append(result)

print(final)

打印:

[['a', 'b', 'c', 'd', 'g', 'h', 'i'],
['a', 'b', 'c', 'e', 'g', 'h', 'j'],
['a', 'b', 'c', 'f', 'g', 'h', 'k']]

然后,您可以根据需要将final分配给mylist

说明

第一个分配将您提供的列表分配给l,然后删除多余的嵌套列表。

然后我们定义一些变量,并且有一个嵌套循环。 Count变量用于计算d,e,f和i,j,k迭代,内部for循环将a,b,c,g,h附加到result以及d,e,f和i中的一个,j,k。在第二次迭代中,它将是e,j,第三次将是f,k,并在每次result循环迭代中将final列表追加到while列表中。

答案 1 :(得分:0)

与其他答案类似,除了它可以缩放到更长的嵌套列表。

mylist = [['a', 'b', 'c', ['d', 'e', 'f'], 'g', 'h', ['i', 'j', 'k']]]

counter = 0
tempmylist = []
newmylist = []
nestedlistlength = 0

while True:
    for i in mylist[0]:
        if type(i) == list:
            if len(i) > nestedlistlength:
                nestedlistlength = len(i)
            try:
                tempmylist.append(i[counter])
            except:
                continue
        else:
            tempmylist.append(i)
    newmylist.append(tempmylist)
    tempmylist = []
    counter += 1
    if counter == nestedlistlength:
        break

print(newmylist)

输出:

[['a', 'b', 'c', 'd', 'g', 'h', 'i'], ['a', 'b', 'c', 'e', 'g', 'h', 'j'], ['a', 'b', 'c', 'f', 'g', 'h', 'k']]