【问题标题】:How to insert a string at the beginning of all items in a list?如何在列表中所有项目的开头插入一个字符串?
【发布时间】:2022-01-15 09:55:12
【问题描述】:

我正在尝试将字符串列表插入到数字列表中。所以我有一个如图所示的字符串列表,我只想将字符串列表的第一个索引附加到第一个列表中所有项目的第一个索引。

输入:['Box_1', 'Box_2, 'Box_3', etc] 输入2:[[0, 1, 1, 2], [2, 5, 7, 8], [4, 6, 6, 7]]

所需输出:[['Box_1_0', 'Box_1_1', Box_1_1', 'Box_1_2'], ['Box_2_2', 'Box_2_5', 'Box_2_7', 'Box_2_8'], etc]

这是我目前所拥有的,但它不起作用

for box_list in time_list:
    l = []
    n = 0
    for batch_num in new_list_files[n]:
        n +=1
        for i in batch_list:
            i = batch_num + str(i)
            l.append(l)
    list_final.append(l)

【问题讨论】:

  • time_list 是数字列表,new_list_files 是字符串列表
  • “不工作”到底是什么意思?
  • list_final = [[f"{box}_{i}" for i in time] for time, box in zip(time_list, new_list_files)]
  • 感谢约翰尼的工作

标签: python python-3.x string list


【解决方案1】:

你去,还要确保你的盒子列表有正确的语法:

box_list = ['Box_1', 'Box_2', 'Box_3']
time_list = [[0, 1, 1, 2], [2, 5, 7, 8], [4, 6, 6, 7]]

new_list = []

for i in box_list:
    for time in time_list:
        new_list.append([f'{i}_{x}' for x in time])

print(new_list)

【讨论】:

    【解决方案2】:

    通过使用列表推导,你可以得到这样的东西:

    box_list = ['Box_1', 'Box_2', 'Box_3']
    time_list = [[0, 1, 1, 2], [2, 5, 7, 8], [4, 6, 6, 7]]
    new_list = [ f"{val}_{x}" for idx, val in enumerate(box_list) for x in time_list[idx]]
    print(new_list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2020-01-06
      • 2010-12-16
      • 2019-09-22
      • 2014-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多