【问题标题】:concatenate strings based on ints from a list根据列表中的整数连接字符串
【发布时间】:2014-01-03 17:45:51
【问题描述】:

我有一个类似的问题here,但这是一个不同的问题。我有两个清单。 list0 是字符串列表,list1 是由整数组成的列表列表。

        # In this example are 8 strings
list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
list1 = [ [0, 1], [2], [3], [4,5,6], [7] ...... ]
        # therefore 8 ints, 0 - 7; it always starts with 0.

list0 中的字符串数量与 list1 中的整数数量完全相同。

我想遍历 list1 ([0,1], [2], ...) 的项目,并根据来自 list1 的项目的 int 数连接来自 list0 的字符串。所以new_list[0]+new_list[1] 应该连接,2 和 3 不应该连接,而不是 4+5+6 应该连接等等......我不知道如何在一个 for 循环中做到这一点,因为一个项目中的整数数量可以各不相同。所以我正在寻找的是一个新的串联列表,应该如下所示:

           # 0 and 1         2           3        4  5  6          7
new_list = ["TestTest", "More text", "Test123", "tttabcokokok", "Hello"]

我该怎么做?

【问题讨论】:

    标签: python


    【解决方案1】:

    使用列表推导和str.join():

    new_list = [''.join([list0[i] for i in indices]) for indices in list1]
    

    演示:

    >>> list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
    >>> list1 = [ [0, 1], [2], [3], [4,5,6], [7]]
    >>> [''.join([list0[i] for i in indices]) for indices in list1]
    ['TestTest2', 'More text', 'Test123', 'tttabcokokok', 'Hello']
    

    【讨论】:

    • 我发誓在 Python 中总是有一个单行解决方案。我只是不知道它是什么:)
    【解决方案2】:

    我会选择 operator.itemgetter 和 list-comp*,例如:

    from operator import itemgetter
    
    list0 = ["Test", "Test2", "More text", "Test123", "ttt", "abc", "okokok", "Hello"]
    list1 = [ [0, 1], [2], [3], [4,5,6], [7] ]
    
    new = [''.join(itemgetter(*indices)(list0)) for indices in list1]
    # ['TestTest2', 'More text', 'Test123', 'tttabcokokok', 'Hello']
    

    * 好吧 - 不,我会选择 list-comp - 它更快并且不需要导入...尽管考虑这是一个替代方案...

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多