Python 列表理解使用条件从列表创建不等长列表

标签 python generator list-comprehension

使用列表理解、itertools 或类似函数,是否可以根据条件从一个列表创建两个不相等的列表?这是一个例子:

main_list = [6, 3, 4, 0, 9, 1]
part_list = [4, 5, 1, 2, 7]

in_main = []
out_main = []

for p in part_list:
    if p not in main_list:
        out_main.append(p)
    else:
        in_main.append(p)

>>> out_main
[5, 2, 7]

>>> in_main
[4, 1]

我尽量保持简单,但作为用法示例,main_list 可以是字典中的值,part_list 包含字典键。我需要同时生成两个列表。

最佳答案

只要您没有重复数据,顺序就没有关系。

main_set = set([6, 3, 4, 0, 9, 1])
part_set = set([4, 5, 1, 2, 7])

out_main = part_set - main_set
in_main = part_set & main_set

工作完成。

关于Python 列表理解使用条件从列表创建不等长列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124903/

相关文章:

PHP - 生成器,发送不遵循产出顺序

Python 生成器函数和排列

python - 以惯用的方式在 Python 中遍历 os.walk 中的各个文件

python - 仅添加到是否满足条件

python - 如何方便地读取python中的数字?

python - 评估 Python 中的所有嵌套生成器

python - 将字符串拆分为连续的计数?

python - 列表理解的优雅总结

python - 简单的 python 算法没有按预期运行

python - Matplotlib 窗口出现在后面?