【问题标题】:Creating a nested list using insert() in Python在 Python 中使用 insert() 创建嵌套列表
【发布时间】:2022-12-03 14:51:59
【问题描述】:

我正在尝试找到一种使用内置列表功能从现有的非空列表中创建嵌套列表的方法。

这是一个小例子: a=['Groceries', 'School Fees', 'Medicines', 'Furniture'] 例如,当我尝试 a[0].insert(0, 1000) 时,我遇到了错误。有什么办法吗?

【问题讨论】:

  • a[0] = [a[0]] 不起作用吗?
  • 当你遇到错误你不知道如何解决时,最好分享错误/回溯,而不是希望我们能找出错误是什么。

标签: python list nested-lists


【解决方案1】:

尝试这个

a=['Groceries', 'School Fees', 'Medicines', 'Furniture']
def innerInsert(index, value):
    try:
        a[index].insert(index, value)
    except AttributeError:
        a[index] = []
        a[index].insert(index, value)

innerInsert(0, 10000)
print(a)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多