我需要修改此代码,以替换 数字1和当前小节的编号。所以,第一个 每个小节中的数字总是会增加。
代替
1
2
3
4
1
2
3
4
1
2
3
4
(每个数字都单独一行),我现在打印
1 2 3 4 2 2 3 4 3 2 3 4
,依此类推。
beats_per_measure = 4
measures = 5
for measure in range(0, measures):
for beat in range(1, beats_per_measure + 1):
print(beat)
答案 0 :(得分:1)
也许您需要以下类似的东西。
beats_per_measure = 4
measures = 5
### loop from 1 to 5 measures ###
# remove +1 to get sequence of 4
# iterations
for measure in range(1, measures+1):
# print the measure value in a single line
# first at iteration of outer loop to get
# the sequence
print(measure, end = " ")
## then loop from 2 to measure
for beat in range(2, beats_per_measure + 1):
# print each beat
print(beat, end = " ")
输出
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
答案 1 :(得分:0)
您可以通过手动打印当前所在的小节来解决此问题-紧随其后的是剩余节拍:
beats_per_measure = 4
measures = 5
for m in range(measures):
# manually print the measure you are in
print(m+1, end=" ") # do not put a newline after the print statement
# print the beats 0...bmp-1 == 0,1,2 - output adds 2 to each => 2,3,4
for beat in range(beats_per_measure - 1):
print(beat+2, end = " ") # do not put a newline after the print statement
输出:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
* * * * *
*是手动打印的,其余的由for
循环填充
您可以在此处阅读有关单行打印的更多信息:
Doku:https://docs.python.org/3/library/functions.html#print
您还可以创建一个生成器,该生成器自己对小节进行计数(我将用*手动标记小节编号):
def gimme_measure(beats_per_measure):
beats = list(range(2,beats_per_measure+1))
yield gimme_measure.measure
gimme_measure.measure += 1
yield from beats
gimme_measure.measure = 1 # defines the starting measure
# print 2*10 measures
for _ in range(10):
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
for _ in range(10): # continues the beat measuring
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
输出:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4 6 2 3 4 7 2 3 4 8 2 3 4 9 2 3 4 10 2 3 4 11 2 3 4 12 2 3 4 13 2 3 4 14 2 3 4 15 2 3 4 16 2 3 4 17 2 3 4 18 2 3 4 19 2 3 4 20 2 3 4
* * * * * * * * * ** ** ** ** ** ** ** ** ** ** **
生成器gimme_measure
拥有自己的度量计数器,每次使用生成器生成新度量时,该计数器都会初始化为1,并且如果不将gimme_measure.measure
重置为其他数字,它将保持不变每当您打印另一个生成的度量时,都向上计数。
您甚至可以将不同的bpm链接在一起:
# piece with 2 measures of 4 beats, 2 measures of 8 beats, 2 measures of 3 beats
for _ in range(2):
print(*gimme_measure(4), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(8), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(3), end = " ")
输出:
1 2 3 4 2 2 3 4 3 2 3 4 5 6 7 8 4 2 3 4 5 6 7 8 5 2 3 6 2 3
* * * * * *
答案 2 :(得分:0)
如果您使用的是python 3,这是答案(已测试):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print(measure, end = ' ')
for beat in range(2, beats_per_measure + 1):
print(beat, end = ' ')
或者,如果您使用的是python 2,请使用此(已测试):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print measure,
for beat in range(1, beats_per_measure + 1):
print beat,
此处有更多信息:https://www.quora.com/How-do-I-print-something-on-the-same-line-in-Python