【问题标题】:Cycle through lists based on different list?根据不同的列表循环浏览列表?
【发布时间】:2021-06-14 20:45:55
【问题描述】:

我想根据我的第二个列表 changes 循环浏览我的第一个列表 c

我希望看到的结果是:

60, 71, 62, 69, 64, 71, 64, 67.

目前,它只打印列表c。我的changes 的真实列表总共有 64 个号码。

对于上下文,列表c 是 C 大调音阶的 midi 值。

我怎样才能做到这一点?我相信这很简单。

C = [60, 62, 64, 65, 67, 69, 71]

changes = [0, 6, 2, 4, 4, 4, 3, 2]

for notes in C:
    print(notes)

【问题讨论】:

  • 你确定这是你想要的输出吗? changes 的第三个元素是2C[2]64。为什么您期望 62 而不是 64 作为输出的第三个元素?

标签: python list iteration


【解决方案1】:

试试:

C = [60, 62, 64, 65, 67, 69, 71]
changes = [0, 6, 2, 4, 4, 4, 3, 2]

output = []
idx_current = 0
for x in changes:
    idx_current = (idx_current + x) % len(C)
    output.append(C[idx_current])

print(output) # [60, 71, 62, 69, 64, 71, 64, 67]

根据您的输出,我猜您想增加C 的索引,同时在必要时进行环绕。这是在idx = (idx + d) % len(C) 行中完成的,即以len(C) 为模增加索引。

或者,对于 Python 3.8+ 使用 Assignment expression,您可以这样做(具有相同的想法)

idx_cur = 0
idx = [idx_cur := (idx_cur + x) % len(C) for x in changes]
output = [C[i] for i in idx]

【讨论】:

  • 啊,原来如此!我想知道 OP 如何从这些索引中获取输出。
  • 谢谢,索引正是我需要的!
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 2016-08-08
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 2019-08-30
相关资源
最近更新 更多