【问题标题】:Append items in front to every list inside list of lists, not to the back将前面的项目附加到列表列表中的每个列表,而不是后面
【发布时间】:2022-01-25 00:47:03
【问题描述】:

我有以下列表。

list_list = 
[
 [1640, 0.1731, 0.173757, 0.1711825, 0.1726265, 4723572.914018], 
 [1640, 0.1726265, 0.1735915, 0.1715855, 0.1734615, 2590512.353352], 
 [1640, 0.1734615, 0.1750445, 0.1731025, 0.1739595, 1803995.1104755], 
]

我想将item_name 附加到列表的前面,使其看起来像这样;

    item_name = "item"
    new_list_list = 
    [
     ["item", "item", 1640, 0.1731, 0.173757, 0.1711825, 0.1726265, 4723572.914018], 
     ["item", "item", 1640, 0.1726265, 0.1735915, 0.1715855, 0.1734615, 2590512.353352], 
     ["item", "item", 1640, 0.1734615, 0.1750445, 0.1731025, 0.1739595, 1803995.1104755], 
    ]

这是我为此编写的 python 代码;

item_name = "item"
new_list_list = [item + [item_name] + [item_name] for item in list_of_list] 

代码将项目附加到列表的后面。我想要的是追加到列表的前面。

我正在使用 python 3.9。

【问题讨论】:

  • 如果你想在开始,为什么item + [item_name] + [item_name]? (虽然我们在这里,为什么不+ [item_name, item_name]?)
  • new_list_list = [[item_name,]*2 + x for x in list_list]

标签: python python-3.x list


【解决方案1】:

尝试:

new_list_list = [[item_name] + [item_name] + item for item in list_of_list]

【讨论】:

  • 呵呵,很好!
  • 谢谢。经核实无误。为什么我没有想到呢?如此简单的改变。
【解决方案2】:

这可能会奏效:

new_list_list = [[item_name] + [item_name] + item for item in list_of_list] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2011-01-31
    • 2019-03-29
    • 2021-03-17
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多