【问题标题】:Add first item of list to front of other list Python将列表的第一项添加到其他列表 Python 的前面
【发布时间】:2020-02-02 17:39:33
【问题描述】:

您好,我想将列表的所有项目插入到矩阵中列表的前面。如此: 我怎样才能解决这个问题?谢谢!

权重矩阵是:

[['tekst4.txt', 'tekst3.txt', 'tekst2.txt', 'tekst1.txt'], 
[0.0, 0.0, 1.0, 1.0], 
[2.0, 0.0, 0.0, 0.0], 
[0.0, 0.0, 0.0, 0.0], 
[0.41503749927884376, 0.8300749985576875, 0.0, 0.41503749927884376]]

需要在列表前面插入的列表:

['', 'noot', 'wim', 'aap', 'mies']

输出应如下所示:

[[' ','tekst4.txt', 'tekst3.txt', 'tekst2.txt', 'tekst1.txt'], 
['noot', 0.0, 0.0, 1.0, 1.0], 
['wim', 2.0, 0.0, 0.0, 0.0], 
['aap', 0.0, 0.0, 0.0, 0.0], 
['mies', 0.41503749927884376, 0.8300749985576875, 0.0, 0.41503749927884376]]

我正在尝试这个:

weight_matrix = [[b.insert(0,i) for i in a] for a, b in zip(weight_matrix, terms)]

【问题讨论】:

    标签: list for-loop matrix insert


    【解决方案1】:

    这可以通过列表理解来完成:

    wm = [['tekst4.txt', 'tekst3.txt', 'tekst2.txt', 'tekst1.txt'], 
    [0.0, 0.0, 1.0, 1.0], 
    [2.0, 0.0, 0.0, 0.0], 
    [0.0, 0.0, 0.0, 0.0], 
    [0.41503749927884376, 0.8300749985576875, 0.0, 0.41503749927884376]]
    
    ad = ['', 'noot', 'wim', 'aap', 'mies']
    
    wm_new = [[ad[i]] + wm[i] for i in range(len(ad))]
    

    结果:

    [['', 'tekst4.txt', 'tekst3.txt', 'tekst2.txt', 'tekst1.txt'], 
    ['noot', 0.0, 0.0, 1.0, 1.0], ['wim', 2.0, 0.0, 0.0, 0.0], 
    ['aap', 0.0, 0.0, 0.0, 0.0], 
    ['mies', 0.41503749927884376, 0.8300749985576875, 0.0, 0.41503749927884376]]
    

    【讨论】:

    • 谢谢!你帮我分配,卡在这几个小时
    • 很高兴为您提供帮助:)
    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多