【发布时间】:2019-03-21 01:24:27
【问题描述】:
我有这段python代码
xy_tups = []
for x in ['m', 't', 'b']:
for y in ['b', 't', 'e']:
if x != y:
xy_tups.append ((x, y))
输出这个:[('m', 'b'), ('m', 't'), ('m', 'e'), ('t', 'b'), ('t', 'e'), ('b', 't'), ('b', 'e')]
我需要创建这段代码的列表理解版本,但我无法弄清楚。这些方法我都试过了
xy_tups = [x for x in ['m', 't', 'b'] and y for y in ['b', 't', 'e'] if x != y]
xy_tups = [x for y in ['m', 't', 'b'] and y for x in ['b', 't', 'e'] if x != y]
并且我尝试将xy_tups.append(x,y) 添加到列表理解代码中,但出现错误。我知道x 列表中的每个字母都与y 列表中的每个字母连接一次,但我不知道如何组合列表理解。
【问题讨论】:
-
docs 有一个例子,几乎和你的问题一模一样。
-
这是一种替代方法,您不仅限于使用列表理解。 stackoverflow.com/questions/46918272/combinations-of-2-lists
标签: python loops nested list-comprehension