代码之家  ›  专栏  ›  技术社区  ›  DaveTheRave

如何在python中向多个列表中插入元素?[重复]

  •  -2
  • DaveTheRave  · 技术社区  · 4 年前

    我有一份清单

    ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23]]
    

    在每个子列表中,我想在末尾插入一个名称,例如。。。

    names = ['Dave', 'Bob']
    
    ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10, 'Dave'], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23, 'Bob']]
    

    当列表变得非常大时,最直接的方法是什么?

    2 回复  |  直到 4 年前
        1
  •  1
  •   Tudor Amariei    4 年前

    一般来说,如果你想把一个项目附加到一个列表中的一个列表中,你可以循环它,然后 append(item) 到列表的末尾。

    for item in ls:
        item.append('Dave')
    

    由于您试图同时对两个列表进行操作,因此可以使用内置的 zip 作用

    ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23]]
    names = ['Dave', 'Bob']
    for list_item, name in zip(ls, names):
        list_item.append(name)
    

    这适用于相同长度的列表。如果您的列表有不同大小的风险,请尝试使用 the answer to this question

        2
  •  -2
  •   Ashish Samarth    4 年前

    试试这样:

    ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23]]
    new_vals = ['Dave', 'Bob']
    
    # Create a function
    # Accept existing list and new values (list) as arguments
    def add_new_elems(_my_list, _new_vals):
        assert len(_my_list) == len(new_vals), 'Length of existing list and new values is not same'
        # Utilize list comprehension to append data
        [_my_list[i].append(_new_vals[i]) for i in range(len(_my_list))]
        return _my_list
    
    
    print(add_new_elems(ls, new_vals))
    ######
    [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10, 'Dave'], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23, 'Bob']]