Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将行号添加到目录列表中_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 将行号添加到目录列表中

Python 将行号添加到目录列表中,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有以下意见: [ {"new": "item"}, {"from": "here"} ] 我是否可以在该项目的索引位置添加一行,例如,以使其最终成为: [ {"idx": 0, "new": "item"}, {"idx": 1, "from": "here"} ] 注意:我还想确保idx的位置在开始处(python3支持dict排序)。您可以使用带有: 输出 [{'idx': 0, 'new': 'item'}, {'from': 'here', 'idx

我有以下意见:

[
    {"new": "item"},
    {"from": "here"}
]
我是否可以在该项目的索引位置添加一行,例如,以使其最终成为:

[
    {"idx": 0, "new": "item"},
    {"idx": 1, "from": "here"}
]
注意:我还想确保idx的位置在开始处(python3支持dict排序)。

您可以使用带有:

输出

[{'idx': 0, 'new': 'item'}, {'from': 'here', 'idx': 1}]
您可以在以下情况下使用:

输出

[{'idx': 0, 'new': 'item'}, {'from': 'here', 'idx': 1}]

oneliner重新创建字典-这非常浪费-分配和创建新dict需要大量的时间/内存等。最好只需迭代字典列表并添加索引键值对:

k = [ {"new": "item"}, {"from": "here"}]

for i,d in enumerate(k):
    d["idx"] = i 

print(k)
输出:

[{'new': 'item', 'idx': 0}, {'from': 'here', 'idx': 1}]

oneliner重新创建字典-这非常浪费-分配和创建新dict需要大量的时间/内存等。最好只需迭代字典列表并添加索引键值对:

k = [ {"new": "item"}, {"from": "here"}]

for i,d in enumerate(k):
    d["idx"] = i 

print(k)
输出:

[{'new': 'item', 'idx': 0}, {'from': 'here', 'idx': 1}]

在python3中,这将把它添加到索引的末尾,任何在开始时获取
索引的方法?@DavidL Try:
{“idx”:i,**e}
?在python3中,这将把它添加到索引的末尾,任何在开始时获取
索引的方法?@DavidL Try:
{“idx”:i,**e}
?请您澄清一下“浪费”是什么意思?它会占用更多的时间/内存吗?或者你的确切意思是什么?谢谢你的更新。可以把它推到第一个位置吗?我希望
idx
列成为第一列。设想一个100个dict的列表,每个都有10个键/值条目-oneliner将创建一个新列表,实例化100个新dict,在每个列表中创建10个键/值。。。要(总共)添加总共100个新密钥。。。如果删除源列表的名称,python可以为此释放资源。。但是,您仍然需要为每个dict仅1个新值实例化许多内容。dict是按输入顺序排列的(3.7/3.6 IPython)-重新排列密钥的唯一方法是重新创建按您喜欢的顺序排序的完整dict。请澄清您所说的“浪费”是什么意思?它会占用更多的时间/内存吗?或者你的确切意思是什么?谢谢你的更新。可以把它推到第一个位置吗?我希望
idx
列成为第一列。设想一个100个dict的列表,每个都有10个键/值条目-oneliner将创建一个新列表,实例化100个新dict,在每个列表中创建10个键/值。。。要(总共)添加总共100个新密钥。。。如果删除源列表的名称,python可以为此释放资源。。但是,您仍然需要为每个dict仅1个新值实例化许多内容。dict是按输入顺序排列的(3.7/3.6 IPython)-重新排列键的唯一方法是重新创建按您喜欢的顺序排列的完整dict