gpt4 book ai didi

python - 加入字符串列表的列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:19 25 4
gpt4 key购买 nike

我有一个列表列表,其中每个元素都是一个字符:

 ngrams = [['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'],
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']]

据此,我想生成一个包含内容 ['aa','ab','ac','ba','bb','bc','ca',' cb','cc']。每个列表的各个元素相互附加,但顺序与列表相反。我想出了这个(其中 np = 2):

for cnt in range(np-2,-1,-1):
thisngrams[-1] = [a+b for (a,b) in zip(thisngrams[-1],thisngrams[cnt])]

我的解决方案需要处理高于 2 的 np。我希望这是 O(np),这还不错。有人可以建议一种更有效的 pythonic 方法来做我想做的事(或者这是一种很好的 pythonic 方法)吗?

最佳答案

你可以试试这个:

ngrams = [['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'],
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']]

new = map(''.join, zip(*ngrams))

输出:

['aa', 'ba', 'ca', 'ab', 'bb', 'cb', 'ac', 'bc', 'cc']

对于两个以上的元素:

n = [["a", "b", "c"], ["a", "c", "d"], ["e", "f", "g"]]

new = map(''.join, zip(* reversed(ngrams)))

#in Python3
#new = list(map(''.join, zip(* reversed(ngrams))))

输出:

['eaa', 'fcb', 'gdc']

关于python - 加入字符串列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632877/

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