首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接列表项

连接列表项
EN

Stack Overflow用户
提问于 2016-02-17 12:16:19
回答 2查看 88关注 0票数 4

我需要做一些必须很容易的事情,但由于某些原因,我无法做到。

因此,基本上,我需要生成一个新的列表,它可以将三个列表中的项目连接起来。

请注意,这三个列表目前都在字典a中。

为了清晰起见,我想做的是:

代码语言:javascript
复制
def test(phrase):
    a = {}
    tmp = phrase.split(' ')
    for m in xrange(0,len(tmp)):

        a[m] = anagrammes2(tmp[m])
        # The anagram function will spit out the anagrams of the words
        # a[1] = ['mange']
        # a[2] = ['ton, 'ont']
        # a[3] = ['orange','onagre','organe','rongea']

test('Mange ton orange')

#result should be:
['mange ont onagre', 'mange ont orange', 'mange ont orangé', 'mange ont organe', 
 'mange ont rongea', 'mange ton onagre', 'mange ton orange', 'mange ton orangé', 
 'mange ton organe', 'mange ton rongea', 'mangé ont onagre', 'mangé ont orange', 
 'mangé ont orangé', 'mangé ont organe', 'mangé ont rongea', 
 'mangé ton onagre', 'mangé ton orange', 'mangé ton orangé', 
 'mangé ton organe', 'mangé ton rongea']
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-17 12:49:37

您可以使用itertools.product()

代码语言:javascript
复制
>>> a = [['mange'], ['ton', 'ont'], ['orange','onagre','organe','rongea']]
>>> from itertools import product
>>> [' '.join(x) for x in product(*a)]
['mange ton orange',
 'mange ton onagre',
 'mange ton organe',
 'mange ton rongea',
 'mange ont orange',
 'mange ont onagre',
 'mange ont organe',
 'mange ont rongea']

与您的代码集成:

代码语言:javascript
复制
def test(phrase):
    anas = [anagrammes2(word) for word in phrase.split(' ')]
    return [' '.join(x) for x in product(*anas)]

test('Mange ton orange')
票数 1
EN

Stack Overflow用户

发布于 2016-02-17 12:22:41

假设它们是字符串:

代码语言:javascript
复制
result = tuple(listA[x % len(listA)] + listB[x % len(listB)] + listC[x % len(listC)] for x in range(max(len(listA), len(listB), len(listC))))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35456478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档