- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我有两个列表
a = [1,2,3]
b = [9,10]
我想将这两个列表合并(压缩)成一个列表 c
这样
c = [(1,9), (2,10), (3, )]
Python 的标准库中是否有任何函数可以做到这一点?
最佳答案
通常,您使用 itertools.zip_longest
为此:
>>> import itertools
>>> a = [1, 2, 3]
>>> b = [9, 10]
>>> for i in itertools.zip_longest(a, b): print(i)
...
(1, 9)
(2, 10)
(3, None)
但是 zip_longest
用 None
填充较短的可迭代对象(或作为 fillvalue=
参数传递的任何值)。如果这不是您想要的,那么您可以使用 comprehension过滤掉 None
s:
>>> for i in (tuple(p for p in pair if p is not None)
... for pair in itertools.zip_longest(a, b)):
... print(i)
...
(1, 9)
(2, 10)
(3,)
但请注意,如果任何一个可迭代对象具有 None
值,这也会将它们过滤掉。如果您不希望这样,请为 fillvalue=
定义您自己的对象并过滤它而不是 None
:
sentinel = object()
def zip_longest_no_fill(a, b):
for i in itertools.zip_longest(a, b, fillvalue=sentinel):
yield tuple(x for x in i if x is not sentinel)
list(zip_longest_no_fill(a, b)) # [(1, 9), (2, 10), (3,)]
关于python - 大小不等的压缩列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11318977/
谁能解释为什么这些 JavaScript 数组不等式比较的计算结果为真? [""] !== [""] [1] !== [1] [] !== [] [""] != [""] [1] != [1] []
好的,所以我一直在努力学习掌握子进程并正确地等待它们完成。我已经阅读了很多 Stack Overflow Q/A,但我似乎仍然无法按照我的意愿让它工作。我一直在阅读/搜索这本书(C++ Primer
根据this , !==! 是不等于字符串运算符。尝试一下,我得到: C:\> if "asdf" !==! "fdas" echo asdf !==! was unexpected at this
这是一道面试题: Suppose: I have 100 trillion elements, each of them has size from 1 byte to 1 trillion byte
如何集成功能 f(y) w.r.t 时间;即 'y'是一个包含 3000 个值和值 time(t) 的数组从 1 到 3000 不等。所以,在整合 f(y) 后我需要 3000 个值. 积分将是不确定
我是一名优秀的程序员,十分优秀!