【问题标题】:How to 'update' or 'overwrite' a python list如何“更新”或“覆盖”python 列表
【发布时间】:2014-10-14 03:39:54
【问题描述】:
aList = [123, 'xyz', 'zara', 'abc']
aList.append(2014)
print aList

产生 o/p [123, 'xyz', 'zara', 'abc', 2014]

应该如何覆盖/更新此列表。 我希望 o/p 是

[2014, 'xyz', 'zara', 'abc']

【问题讨论】:

    标签: python list overriding overwrite


    【解决方案1】:

    你可以试试这个

    alist[0] = 2014
    

    但如果你不确定 123 的位置,那么你可以这样尝试:

    for idx, item in enumerate(alist):
       if 123 in item:
           alist[idx] = 2014
    

    【讨论】:

    • 为什么使用in 来比较列表项(数字..)?
    • 不应该是if 123 == item吗?如果有12345怎么办?
    【解决方案2】:

    如果知道位置,如何替换项目:

    aList[0]=2014
    

    或者如果你不知道列表中的位置循环,找到该项目然后替换它

    aList = [123, 'xyz', 'zara', 'abc']
        for i,item in enumerate(aList):
          if item==123:
            aList[i]=2014
            break
        
        print aList
    

    【讨论】:

    • 找到目标项目后为什么没有break
    • 按建议编辑
    【解决方案3】:

    我认为它更pythonic:

    aList.remove(123)
    aList.insert(0, 2014)
    

    更有用:

    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']
    

    【讨论】:

    • 这仅适用于整数而不是如果我想插入 def 代替 abc。我想要一个通用的解决方案.. 不是硬编码的。
    • 我不知道你为什么这么认为,pyLearner。请花一些时间阅读 Python 列表的文档。
    • 与直接就地替换元素相比,这是一个非常低效的解决方案(例如 Kerby 的解决方案)
    【解决方案4】:

    我正在学习编码,我发现了同样的问题。我相信解决这个问题的更简单方法是从字面上覆盖@kerby82 所说的列表:

    Python 中列表中的项目可以使用表单设置为一个值

    x[n] = v

    其中 x 是列表的名称,n 是数组中的索引,v 是您要设置的值。

    在你的例子中:

    aList = [123, 'xyz', 'zara', 'abc']
    aList[0] = 2014
    print aList
    >>[2014, 'xyz', 'zara', 'abc']
    

    【讨论】:

      【解决方案5】:

      我更喜欢不枚举,而是像这样使用“范围”:

      for item in range(0, len(alist)):
         if 123 in alist[item]:
            alist[item] = 2014
      

      对于那些不熟悉 python 的人来说,它可能更具可读性和更聪明的回顾。

      问候 P.

      【讨论】:

        【解决方案6】:

        如果您尝试从同一个数组中获取一个值并尝试更新它,您可以使用以下代码。

        {  'condition': { 
                             'ts': [   '5a81625ba0ff65023c729022',
                                       '5a8161ada0ff65023c728f51',
                                       '5a815fb4a0ff65023c728dcd']}
        

        如果集合是userData['condition']['ts'],我们需要

            for i,supplier in enumerate(userData['condition']['ts']): 
                supplier = ObjectId(supplier)
                userData['condition']['ts'][i] = supplier
        

        输出将是

        {'condition': {   'ts': [   ObjectId('5a81625ba0ff65023c729022'),
                                    ObjectId('5a8161ada0ff65023c728f51'),
                                    ObjectId('5a815fb4a0ff65023c728dcd')]}
        

        【讨论】:

          猜你喜欢
          • 2014-05-29
          • 2019-11-14
          • 2015-01-15
          • 2020-11-17
          • 1970-01-01
          • 1970-01-01
          • 2010-09-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多