python - 列表和元组之间的连接/分布

标签 python list tuples list-comprehension

我有以下示例。

prefix = ['blue ','brown ']
suffix = [('dog','shoes','bike'), ('tree','cat','car')]

我想获得一个如下所示的新列表:

[('blue dog', 'blue shoes', 'blue bike'),
 ('blue tree', 'blue cat', 'blue car'),
 ('brown dog', 'brown shoes', 'brown bike'),
 ('brown tree', 'brown cat', 'brown car')]

也就是说,我想将第一个列表的每个元素与第二个列表中每个元组中的每个项目进行分发和连接。第二个列表可以有 2 个以上的元组,但每个元组始终只有 3 个项目。

有什么办法可以做到这一点而不必编写嵌套的 for 循环吗?

最佳答案

使用嵌套列表理解:

lst = [tuple(i+x for x in j) for i in prefix for j in suffix]
print(lst)
# [('blue dog', 'blue shoes', 'blue bike'), 
# ('blue tree', 'blue cat', 'blue car'), 
# ('brown dog', 'brown shoes', 'brown bike'), 
# ('brown tree', 'brown cat', 'brown car')]
<小时/>

您可以将推导式展开为 for 循环,以更好地理解它是如何工作的:

lst = []
for i in prefix:
   for j in suffix:
      lst.append(tuple(i+x for x in j))

关于python - 列表和元组之间的连接/分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42597817/

相关文章:

python - ValueError:未知层:加载keras模型时的名称

python - 访问列表中元组中的值

python - 为什么字典键没有改变

c - 如何建立链接: chained list and pointer in c

java - 使用 ListIterator 且是唯一列表的集合

list - Haskell:从输入列表创建列表元组

json - 二郎 : Tuple List into JSON

python - 用 Python 解析

python - 使用正则表达式替换 Pandas 数据框中字符串的特定部分

python - 如何在列表中构建字典数据?