gpt4 book ai didi

python - 根据列表中的整数连接字符串

转载 作者:太空宇宙 更新时间:2023-11-03 12:24:21 25 4
gpt4 key购买 nike

我有一个类似的问题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], ...) 的项目,并根据来自 列表1。所以 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"]

我该怎么做?

最佳答案

使用列表理解和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 - 根据列表中的整数连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20909632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com