[英]How to 'update' or 'overwrite' a python list
aList = [123, 'xyz', 'zara', 'abc']
aList.append(2014)
print aList
which produces o/p [123, 'xyz', 'zara', 'abc', 2014]
产生 o/p
[123, 'xyz', 'zara', 'abc', 2014]
What should be done to overwrite/update this list.应该做什么来覆盖/更新这个列表。 I want the o/p to be
我希望 o/p 是
[2014, 'xyz', 'zara', 'abc']
You may try this你可以试试这个
alist[0] = 2014
but if you are not sure about the position of 123 then you may try like this:但是如果您不确定 123 的位置,那么您可以尝试这样:
for idx, item in enumerate(alist):
if 123 in item:
alist[idx] = 2014
What about replace the item if you know the position:如果您知道位置,那么更换物品怎么样:
aList[0]=2014
Or if you don't know the position loop in the list, find the item and then replace it或者如果你不知道列表中的位置循环,找到该项目然后替换它
aList = [123, 'xyz', 'zara', 'abc']
for i,item in enumerate(aList):
if item==123:
aList[i]=2014
break
print aList
I think it is more pythonic:我认为它更像pythonic:
aList.remove(123)
aList.insert(0, 2014)
more useful:更有用:
def shuffle(list, to_delete, to_shuffle, index):
list.remove(to_delete)
list.insert(index, to_shuffle)
return
list = ['a', 'b']
shuffle(list, 'a', 'c', 0)
print list
>> ['c', 'b']
I'm learning to code and I found this same problem.我正在学习编码,我发现了同样的问题。 I believe the easier way to solve this is literaly overwriting the list like @kerby82 said:
我相信解决这个问题的更简单的方法是像@kerby82 所说的那样覆盖列表:
An item in a list in Python can be set to a value using the form Python 中列表中的项目可以使用以下形式设置为一个值
x[n] = v x[n] = v
Where x is the name of the list, n is the index in the array and v is the value you want to set.其中x是列表的名称, n是数组中的索引, v是您要设置的值。
In your exemple:在你的例子中:
aList = [123, 'xyz', 'zara', 'abc']
aList[0] = 2014
print aList
>>[2014, 'xyz', 'zara', 'abc']
I would prefer it without enumerate and instead use "range" like this:我更喜欢不枚举,而是使用“范围”,如下所示:
for item in range(0, len(alist)):
if 123 in alist[item]:
alist[item] = 2014
For those who are new to python it might be more readable and a little smarter to recap.对于那些不熟悉 python 的人来说,它可能更具可读性,而且回顾起来也更聪明一些。
Regards P.问候P。
If you are trying to take a value from the same array and trying to update it, you can use the following code.如果您尝试从同一个数组中获取一个值并尝试更新它,您可以使用以下代码。
{ 'condition': {
'ts': [ '5a81625ba0ff65023c729022',
'5a8161ada0ff65023c728f51',
'5a815fb4a0ff65023c728dcd']}
If the collection is userData['condition']['ts'] and we need to如果集合是 userData['condition']['ts'] 并且我们需要
for i,supplier in enumerate(userData['condition']['ts']):
supplier = ObjectId(supplier)
userData['condition']['ts'][i] = supplier
The output will be输出将是
{'condition': { 'ts': [ ObjectId('5a81625ba0ff65023c729022'),
ObjectId('5a8161ada0ff65023c728f51'),
ObjectId('5a815fb4a0ff65023c728dcd')]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.