【问题标题】:how do I append something to a list after an element not at the end of the list如何在不在列表末尾的元素之后将某些内容附加到列表中
【发布时间】:2021-12-30 15:30:37
【问题描述】:

我有一个清单...

   delimiterList = ["[", "]", "{", "}", ","]

def getData():
    Input = input("Enter JSON")
    return Input

def saveInputAsList(input):
    inputList = []
    for i in input:
        inputList.append(i)
    return inputList

def Format():
    input = saveInputAsList(getData())
    if delimiterList in input:
        input.append('\n')
        return input
        
 

print(Format())
  1. 询问用户输入,保存到列表我想循环浏览列表
  2. 如果用户输入中我的分隔符列表中的任何字符串将“\n”附加到列表中
  3. 输出应该是 ['a', '"', '\n', 'b', '[', '\n']

我正在尝试在不使用库的情况下处理 JSON 美化器

【问题讨论】:

  • 要打印 JSON,您可以使用 json.dumps,请参阅 stackoverflow.com/a/12944035/8271728
  • @SteveMapes 这个我知道,我以前用过。我正在尝试在没有库的情况下编写自己的格式化程序

标签: python json


【解决方案1】:

您可以在列表上使用插入方法。见python文档here

此方法将帮助您在给定索引处插入元素。如果您要查找列表中第一次出现的元素,可以使用index 方法。

所以:


my_list = ['a', 'b', 'c']
my_list.insert(my_list.index('b') + 1, 'z')
print(my_list)

会输出

['a', 'b', 'z', 'c']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多