如何插入python嵌套列表 [英] How to insert into python nested list

查看:74
本文介绍了如何插入python嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个项目插入列表中的列表中.我想知道是否有人可以给我看.

I want to insert an item into a list inside a list. I'm wondering if someone can show me.

list5 = [[], [(1,2,3,4), 2, 5]]
print("1. list5", list5)
list5.insert(0, (2,5,6,8))
print("2. list5", list5)

Output:
1. list5 [[], [(1, 2, 3, 4), 2, 5]]
2. list5 [(2, 5, 6, 8), [], [(1, 2, 3, 4), 2, 5]]

我想要:

2. list5 [[(2, 5, 6, 8)], [(1, 2, 3, 4), 2, 5]]

不幸的是,字典无法正常工作.

A dictionary unfortunately won't work.

推荐答案

问题是您正试图插入不正确的列表list5作为列表的第一个元素.您必须访问列表的第一个元素并将其插入该列表.可以使用以下代码完成

The problem is you are trying to insert as the first element of the list, list5 which is incorrect. You have to access the first element of the list and insert it to that list. This can be done using the following code

>>> list5 = [[], [(1,2,3,4), 2, 5]]
>>> print("1. list5", list5)
1. list5 [[], [(1, 2, 3, 4), 2, 5]]
>>> list5[0].insert(0, (2,5,6,8))
>>> print("2. list5", list5)
2. list5 [[(2, 5, 6, 8)], [(1, 2, 3, 4), 2, 5]]

这篇关于如何插入python嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆