简体   繁体   English

Python 列表和多维列表的区别

[英]Python difference between a list and multi-dimensional list

I need some help, the following is what I want:我需要一些帮助,以下是我想要的:

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
list2 = ["b", "c"]
list3 = []

list1 - list2 = list3
print(list3)

Expected Output:
[["a", "1"], ["d", "4"]]

I know that you can do the following with one-dimensional lists:我知道您可以使用一维列表执行以下操作:

list1 = ["a", "b", "c", "d"]
list2 = ["b", "c"]

list3 = list(set(list1) - set(list2))
print(list3)

Output: ["a", "d"]

So, how do I do the above but with multi-dimensional lists and output of a multi-dimensional list as well?那么,除了多维列表和多维列表的输出之外,我该如何执行上述操作?

G. Anderson is right, it seems that you're in a good use case for dictionnaries. G. Anderson 是对的,看来您是字典的一个很好的用例。

If you'll stuck with this data structure (that could be the case if your inner lists can have more than 2 elements), you'll have to use list comprehension , this syntax is not supported out-of-the-box.如果您坚持使用此数据结构(如果您的内部列表可以有 2 个以上的元素,则可能是这种情况),您将必须使用列表理解,此语法不支持开箱即用。

my suggestion我的建议

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
ignored_keys = ['b', 'c']
list3 = [val for val in list1 if val[0] not in ignored_keys]
print(list3)
Output: [['a', '1'], ['d', '4']]

You can try with list comprehension.您可以尝试使用列表理解。 Essentially what we are doing is, retaining the sublists from list1 that their first value (the character) does not exists in the values of list2:基本上我们正在做的是,保留list1中的子列表,它们的第一个值(字符)不存在于 list2 的值中:

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
list2 = ["b", "c"]

list3 = [item for item in list1 if item[0] not in list2]
print(list3)

Output:输出:

[['a', '1'], ['d', '4']]

However this is to solve this particular example with the particular data you provide.但是,这是为了使用您提供的特定数据解决此特定示例。 As explained in comments, working with dictionaries is recommended.正如评论中所解释的,建议使用字典。

Here's another answer using filter and a lambda function.这是使用过滤器和 lambda 函数的另一个答案。

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
list2 = ["b", "c"]
list3 = []

list3 = list(filter(lambda x: x[0] not in list2, list1))
print(list3)

# [["a", "1"], ["d", "4"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM