- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
(在我开始之前,让我们假设这是一个面试问题,我的目的是避免仅仅调用 sorted。)
我有这段有效的 Python 代码:
def merge_sorted_lists(left, right):
leftlen = len(left)
rightlen = len(right)
leftidx = 0
rightidx = 0
newlist = []
while leftidx < leftlen or rightidx < rightlen:
if rightidx == rightlen or left[leftidx] <= right[rightidx]:
newlist.append(left[leftidx])
leftidx += 1
elif leftidx == leftlen or right[rightidx] < left[leftidx]:
newlist.append(right[rightidx])
rightidx += 1
return newlist
我是一名长期的 C++ 程序员,最近学习了足够多的 Python,知道这“闻起来”非常不符合 Pythonic 的习惯,因为 idx 的大量使用。当迭代器的推进需要这种微调控制时,是否有更优雅的方式来迭代两个列表?
最佳答案
呃,作为第一个猜测,我会先尝试使用生成器。我使用 yield 而不是构建列表,因为 a) 生成器可以是无限的,并且 b) 嘿,一旦你开始使用生成器,不妨一直使用生成器。
def merge(left,right):
left = iter(left)
right = iter(right)
left_val = next(left)
right_val = next(right)
try:
while True:
if left_val <= right_val:
yield left_val
left_val = next(left) #left.next() in python2
else:
yield right_val
right_val = next(right)
except StopIteration: #I have exhausted one of the iterators
if left_val <= right_val:
#left list depleted
yield right_val
for i in right: yield i #or use yield from right, if your python is fancy enough
else:
#right list depleted
yield left_val
for i in left: yield i
In [2]: f = merge([0,4,17],[2,4,5,6,6,6])
In [3]: list(f)
Out[3]: [0, 2, 4, 4, 5, 6, 6, 6, 17]
关于单步执行两个列表并避免 idx 的 Pythonic 风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616096/
我正在尝试使用范围输入元素构建一个 slider ,该元素在单击、滚动或长按(连续按下)时移动 1 步。我有点击和滚动所需的逻辑,但是相同的逻辑似乎不适用于鼠标按下事件(长按/连续按下)。 到目前为止
我正在编写一个跟踪其他程序执行情况的程序。我正在使用动态指令检测来跟踪 x86 的 CMP 指令的行为。 我正在使用 Windows 调试 API 来控制被调试程序的行为。我使用“仅调试此进程”标志启
我有以下代码片段。 我有点困惑,首先,为什么我的步骤参数是2,是不是因为我从字典之外跳转,所以我最终得到了总人口? 第二:i+1 到底是做什么的?以前没见过吗?如果我从 i (国家名称)跳到总人口上,
如果我同时拥有公钥和私钥,如何使用 everyauth 通过 node.js 执行非常简单的 oauth 身份验证?与多步骤 facebook 类型的身份验证不同,我只想使用 everyauth 进行
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 2年前关闭。 Improve thi
我是一名优秀的程序员,十分优秀!