根据列表中的int来连接字符串

时间:2014-01-03 17:45:51

标签: python

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

        # 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循环中这样做,因为一个ints的数量项目可能有所不同所以我要找的是一个新的连接列表,应该是这样的:

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

我该怎么做?

2 个答案:

答案 0 :(得分:9)

使用列表推导和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']

答案 1 :(得分:4)

我会去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 - 它更快,不需要导入......考虑这个替代方案,但是......