Python 列表比较和合并

发布于 2024-11-27 14:09:24 字数 358 浏览 1 评论 0原文

我有 2 个列表:

correct_list = [1,2,3,4,5,6,7,8,9,10]
other_list = [4,5,6,7,8,10]

我想将这两个列表合并起来:

combined_list = [{k:1, v:0},{k:2, v:0},{k:3, v:0}, {k:4, v:4}, {etc}]

所以基本上是说关键是正确的列表,并且在 other_list 与 Correct_list 不匹配的地方,填写 0 或 " " 。并且他们确实匹配,填写匹配值

这有意义吗?

我将如何在 python 中执行此操作?

I have 2 lists:

correct_list = [1,2,3,4,5,6,7,8,9,10]
other_list = [4,5,6,7,8,10]

I would like to combine these two lists so:

combined_list = [{k:1, v:0},{k:2, v:0},{k:3, v:0}, {k:4, v:4}, {etc}]

so basically am saying that the key is the correct list, and where ever the other_list does not match the correct_list, fill in a 0, or " " . And of they do match, fill in the matching value

Does this makes sense ?

How would I do this in python ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虚拟世界 2024-12-04 14:09:24
[{'k': c, 'v': c if c in other_list else 0} for c in correct_list]

顺便说一句,如果字典的唯一元素是 k 和 v,请考虑构建一个字典而不是字典列表:

>>> dict((c, c if c in other_list else 0) for c in correct_list)
{1: 0, 2: 0, 3: 0, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 0, 10: 10}
[{'k': c, 'v': c if c in other_list else 0} for c in correct_list]

By the way, if the only elements of the dictionaries are k and v, consider building a dictionary instead of a list of dictionaries:

>>> dict((c, c if c in other_list else 0) for c in correct_list)
{1: 0, 2: 0, 3: 0, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 0, 10: 10}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文