在python中,不是每一项都是列表,如何线性组合列表?

2024-03-29 12:03:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由字符串和列表组成的列表:

a = ['a', 'b', 'c', 'd', 'e', ['fgh', 'rst'], 'i',['quv','wxy']]

如何连接此列表中的每个元素,以便所有字符串元素都包含每个内部列表元素中的一个,同时保持它们在原始列表中的位置?例如:

targets = ['abcdefghiquv',
           'abcdefghiwxy',
           'abcderstiquv',
           'abcderstiwxy',
          ]

我尝试了下面的方式,但是,这只适用于最后一个元素是列表的情况

combinations = []
combinations2 = []
for s in a:
    if isinstance(s, basestring):
        combinations.append(s)
    else:
        seqint = ''.join(combinations)
        combinations2.append([seqint])
        combinations2.append(s)
        combinations[:]=[]
for comb in list(itertools.product(*combinations2)):
    print ''.join(comb)

Tags: 字符串in元素列表forrstjoincomb
1条回答
网友
1楼 · 发布于 2024-03-29 12:03:49

使用itertools.product无疑是一种方法。我会这样做(可能不完全正确,因为我从来没有太多地使用遗留Python):

# helper function
def strtolist(o):
    '''Takes an object and puts it in a list if it's a string'''
    if isinstance(o, str):
        return [o]
    return o

a = ['a', 'b', 'c', 'd', 'e', ['fgh', 'rst'], 'i',['quv','wxy']]
newa = [strtolist(item) for item in a]

最后一步叫做列表理解。它们非常有用,因此可以很好地利用时间去阅读它们(还有字典理解和生成器理解)。你知道吗

现在我们有一个新的列表,如下所示:

newa = [['a'], ['b'], ['c'], ['d'], ['e'], ['fgh', 'rst'], ['i'],['quv','wxy']]

然后像以前一样完成:

from itertools import product

for comb in list(product(*newa)):
    print ''.join(comb)

编辑:如果你真的想变得粗暴,你可以在一个语句中完成所有这些。但我不推荐(不太可读):

>>> result = [''.join(combo) for combo in product(*[([item] if isinstance(item, basestr) else item) for item in a])]
>>> assert result == targets
# no error: success 

似乎您正在学习,所以我要补充一点:除非您有很好的理由学习使用传统Python(2),否则我建议您切换到现代Python(当前版本3.6)。在这一点上,一切都朝着这个方向发展(尽管在许多上下文中,遗留的Python可能还会存在很长一段时间)。你知道吗

网友
2楼 · 发布于 2024-03-29 12:03:49

另一种方法是获取列表索引并使用itertools.产品你知道吗

a = ['a', 'b', 'c', 'd', 'e', ['fgh', 'rst'], 'i',['quv','wxy'] ]
idx = []
lst = []
for i in a:
    if isinstance(i, list):
        idx.append(a.index(i))
        lst.append(i)

from itertools import product

for j in [ dict( zip(idx,i) ) for i in product(*lst) ] :
    for k,v in j.items():
        a[k] = v
    print ( ''.join(a) )
网友
3楼 · 发布于 2024-03-29 12:03:49

作为一种功能样式,您可以reduce列出:

list(reduce(lambda x, y: (x1 + "".join(y1) for x1 in x for y1 in y), a))
['abcdefghiquv', 'abcdefghiwxy', 'abcderstiquv', 'abcderstiwxy']

相关问题 更多 >