【问题标题】:How to you use list comprehension to match values from a two dimensional list to another two dimensional list?如何使用列表推导将二维列表中的值匹配到另一个二维列表?
【发布时间】:2019-09-17 22:58:49
【问题描述】:

例如我有两个列表是二维列表

a=[[7,9,10,11,12],[4,11,14,16,21]]
b=[[5,9,14,15],[7,12,15,17,19],[8,14,15,17,19],[13,15,17,20,22]]

我希望结果是

0. [[9],[12,7]]
1. [[4], [14]]

从您的评论中复制:

for 循环。

for idx,item_a in enumerate(a): 
    result = [] 
    for item_b in b: 
        result.append(list(set(item_a) & set(item_b))) 
    print(idx,result))

【问题讨论】:

  • 你会如何用一个(或两个)for循环来做到这一点?从头开始提出改进代码的建议更容易。哦,使用列表推导式创建两个列表有点棘手(并非不可能,但它涉及额外的转置步骤)。
  • 我真的不想使用 for 循环,因为当我开始新行时,它只显示最后一行。但这就是我的 for 循环。 idx,item_a in enumerate(a): result = [] for item_b in b: result.append(list(set(item_a) & set(item_b))) print(idx,result))
  • [[list(set(i)&set(j)) for i in b] for j in a]
  • 那么result(循环之后)有什么问题?
  • 循环的问题是我无法使用显示器。对不起,我是 python 新手

标签: python python-3.x list nested-lists


【解决方案1】:

如果我正确理解您的问题,此代码适合您

res = list(enumerate([[list(set(x) & set(y)) for x in b] for y in a]))
# output: [(0, [[9], [12, 7], [], []]), (1, [[14], [], [14], []])]

如您所见,res 是一个元组列表,例如:(idx, list_value)
例如res[0] 包含元组(0, [[9], [12, 7], [], []]),其中0 是索引,[[9], [12, 7], [], []] 是对应值列表的列表。为了消除所有疑问,这是代码:

idx0, lst0 = res[0]   # or equivalently idx0, lst0 = res[0][0], res[0][1]
print('idx of res[0] is %d and the corresponding list is: %s' %(idx0, str(lst0)))
# output: idx of res[0] is 0 and the corresponding list is: [[9], [12, 7], [], []]

你可以这样打印所有的结果:

for idx, val in res:
    print(idx, val)

你会得到:

0 [[9], [12, 7], [], []]
1 [[14], [], [14], []]

【讨论】:

  • 这可行,但有一种方法可以放置索引。就像结果描述中的内容一样
  • 我已经更新了答案,现在你也有了与每个列表关联的索引
  • 你能在没有循环的情况下做到这一点吗
  • 当然,它已经在没有循环的情况下完成了......循环仅用于打印结果。我尝试更新答案以使您更好地理解
  • 希望我做得对。你能告诉我它是否有效吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
相关资源
最近更新 更多