Python 之嵌套列表

        嵌套(nest),顾名思义,我中有你,你在我中之意。嵌套是 Python 语言中常见的现象,有函数嵌套,循环嵌套,可迭代对象嵌套等,具体到标题,即指列表中嵌套有列表,形如:

例 1

>>> info = [['张三', 'M', '45'], ['李四', 'F', '36'], ['王五', 'M', '42']]
>>> print(info)
[['张三', 'M', '45'], ['李四', 'F', '36'], ['王五', 'M', '42']]

        类似的还有列表嵌套字典字典嵌套字典字典嵌套列表等,操作方法相近,本文以嵌套列表为例。

索引

        与列表索引一致,嵌套列表索引的语法为:

list_name[index1][index2][...]

        其中,index1 为目标元素所在子列表,index2 为子列表中的目标元素,以此类推……

如提取例 1 中李四的年龄信息:

>>> info[1][2]
'36'

排序

        同列表排序,如例 1 按年龄降序排列:

>>> info.sort(key = lambda x: x[2], reverse = True)
>>> info
[['张三', 'M', '45'], ['王五', 'M', '42'], ['李四', 'F', '36']]

详见:Python 函数 sort(),sorted() 之区别及 key=lambda x:x[] 之理解数据排序Python 之嵌套列表https://blog.csdn.net/iprobobo/article/details/122713695

去重

        关于嵌套列表中对象的去重,需要注意的是,因为嵌套列表为非哈希类型,不能利用集合的去重特性:

例 2

>>> l = [['a', 'b'], ['c', 'd']]
>>> hash(l)
Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    hash(l)
TypeError: unhashable type: 'list'

        若要去重且保持原顺序,可通过列表元素的取出(list.pop())和插入(list.insert())遍历实现(感谢 技术专家团-Plio大咸鱼 的指导):

例 3 

l = [['百度', 'BD'], ['京东', 'JD'], ['淘宝', 'TB'], ['百度', 'BD']]
L = []
while(l):
    pop_l = l.pop()
    if pop_l in l:
        continue
    else:
        L.insert(0, pop_l)
print(L)

        运行结果:

[['百度', 'BD'], ['京东', 'JD'], ['淘宝', 'TB']]

        若是复杂的多层嵌套,可借助自定义函数递归:

例 4

l = [['百度', 'BD'], ['京东', 'JD'], [['百度', 'BD'], ['淘宝', 'TB']]]
L = [] 
 
def f(l, L): 
    while(l):
        pop_l = l.pop()
        if type(pop_l[0]) == list:
            f(pop_l, L)
        else:
            if pop_l in L:
                continue
            else:
                L.insert(-1, pop_l)
 
f(l, L)
print(L)

 运行结果:

[['百度', 'BD'], ['京东', 'JD'], ['淘宝', 'TB']]

展平

        将单层嵌套列表展平为非嵌套列表,可借助列表 extend() 函数:

例 5

l = [['a', 'b'], ['c', 'd']]
L = []
for i in l:
    L.extend(i)
print(L)

        运行结果:

['a', 'b', 'c', 'd']

        或借助列表推导式:

例 6

>>> l = [[1, 2], [3, 4, 5], [6, 7], [8], [9]]
>>> L = [x for y in l for x in y]
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9]

        对于复杂的多层嵌套列表,可借助递归:

例 7

l = [1, [2], [[3]], [[4, [5]], 6]]
L = []

def f(l, L):    
    for i in l:
        if isinstance(i, list):
            f(i,L)
        else:
            L.append(i)

f(l,L)
print(L)

运行结果:

[1, 2, 3, 4, 5, 6]

        也可以利用生成器来迭代:

例 8

def f(x):
    for i in x:
        if isinstance(i, list):
            yield from f(i)
        else:
            yield i
            
l = [[4, [2, 3], [[[7], 5]], [[[9, [1]]], 8], 6]]
L = [x for x in f(l)]

print(sorted(L))

运行结果:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

附:

列表嵌套字典

        在列表中嵌套字典为常用的方式:

例 9

l = [{'a': 3}, {'b': 2}, {'c': 1}]
L = []

for i in range(len(l)):
    for j in l[i].items():
        L.append(j)
        
print(L)

运行结果:

[('a', 3), ('b', 2), ('c', 1)]

字典嵌套字典

        此时字符串为 key,嵌套的字典为 value:

>>> d = {'a':{'b':'Yes','c':{'d':{'e': 'or', 'f': 'No'}}},'g':{}}
>>> d['a']['c']['d']['f']
'No'

字典嵌套列表

        字符串为 key,嵌套的列表为value:

>>> d = {
    '水果':['西瓜','榴莲','芒果'],
    '动物':['狮子','蓝鲸','蚂蚁']
}

>>> print(d['水果'][1])
榴莲

>>> for k, v in d.items():
        print('\n', k, end = ':')
        for i in v:
            print(i, end = ' ')

水果:西瓜 榴莲 芒果 
动物:狮子 蓝鲸 蚂蚁

……

注:

1、关于序列的更多知识总结,请参见:Python 序列之三言两语序列是具有先后关系的一组元素…Python 之嵌套列表https://blog.csdn.net/iprobobo/article/details/122542937

2、关于列表推导式,请参见:Python 之推导式常用的语法糖Python 之嵌套列表https://blog.csdn.net/iprobobo/article/details/123582135 3、关于字典,请参见:Python 字典之演义映射无处不在,键值对无处不在。Python 之嵌套列表https://blog.csdn.net/iprobobo/article/details/122668767

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年4月6日
下一篇 2023年4月6日

相关推荐