Python中的字符串列表乘法

2024-05-29 05:53:48 发布

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

初学者问题: 如果我有两个只包含字符串的列表,如何将它们连接到第三个列表中,其中包含所有元素+一个列表中的每个元素+另一个列表中的每个元素?我考虑过for循环,但是没有更简单的方法吗? 示例:

listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun'] 

resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']

编辑:谢谢大家的回复,但我没有解释我想把什么做好。 每个列表中的字符串数量应该是不确定的,每个单词都必须与其他单词连接起来,但不能仅以“x+y”的形式连接。 我还想把它和其他单词连接起来。比如u=x+y+z


Tags: 方法字符串元素示例列表forbin单词
3条回答

这应该行得通

In [29]: import itertools
In [30]: listone = ['cat', 'dog' ]
    ...: listtwo = ['bin', 'sun']

In [31]: output = listone + listtwo + [ "".join(items)  for items in list(itertools.product(listone, listtwo))]

In [32]: output
Out[32]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']

你也可以不使用itertools

^{pr2}$

在不导入itertools的情况下,在访问listone和{}的元素时,也可以使用字符串连接,如下所示:

result = listone + listtwo + [listone[0] + listtwo[0], listone[0] + listtwo[1], listone[1] + listtwo[0], listone[1] + listtwo[1]]

您可以使用笛卡尔积和连接。尝试以下操作:

import itertools
listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun'] 
listone + listtwo + list(''.join(e) for e in itertools.product(listone, listtwo))

结果:

^{pr2}$

相关问题 更多 >

    热门问题