Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 连接字符串列表的列表_Python_List - Fatal编程技术网

Python 连接字符串列表的列表

Python 连接字符串列表的列表,python,list,Python,List,我有一个列表,其中每个元素都是一个字符: 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): 我的解决方案需要处理比2更高的np

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

 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
):

我的解决方案需要处理比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']
['eaa', 'fcb', 'gdc']
对于两个以上的元素:

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))))
输出:

['aa', 'ba', 'ca', 'ab', 'bb', 'cb', 'ac', 'bc', 'cc']
['eaa', 'fcb', 'gdc']
您可以尝试以下方法:

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']
['eaa', 'fcb', 'gdc']
对于两个以上的元素:

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))))
输出:

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

map('''.join,zip(*ngrams))
超过两个!我想Ryan得到了你想要的,但是如果你还想颠倒列表的顺序,你需要
map('''.join,zip(*reversed(ngrams))
谢谢Carl,我只是用*来解包ngrams[::-1]:-)谢谢你。巨蟒真漂亮!或
map('''.join,zip(*ngrams))
超过两个!我想Ryan得到了你想要的,但是如果你还想颠倒列表的顺序,你需要
map('''.join,zip(*reversed(ngrams))
谢谢Carl,我只是用*来解包ngrams[::-1]:-)谢谢你。巨蟒真漂亮!