目前我有以下列表:
counter = [13]
instruments = ['3\t ---', '2\t / \\', '1\t / \\', '0\t--- \\ ---', '-1\t \\ /', '-2\t \\ /', '-3\t ---']
score = ['|*************|']
Run Code Online (Sandbox Code Playgroud)
我要做的是用乐谱列表中的字符替换乐器列表中的字符(不包括|).
我目前遇到以下问题
字符将逐行替换,而不是逐列替换.
仪器清单:
3 ---
2 / \
1 / \
0 --- \ ---
-1 \ /
-2 \ /
-3 ---
Run Code Online (Sandbox Code Playgroud)
分数列表:
|*************|
Run Code Online (Sandbox Code Playgroud)
预期产量:
3 ***
2 * *
1 * *
0 *** *
-1 *
-2 *
-3
Run Code Online (Sandbox Code Playgroud)
电流输出:
3 ***
2 * *
1 * *
0 *** * **
-1
-2
-3
Run Code Online (Sandbox Code Playgroud)
这就是我目前正在替换instruments列表中的字符的方式:
for elements in counter:
current_counter = elements
count = 0
for elements in instrument_wave:
amplitude, form = elements.split('\t')
for characters in form:
if characters in ['-', '/', '\\']:
form = form.replace(characters, '*', 1)
count += 1
if count == current_counter:
break
for characters in form:
if characters in ['-', '/', '\\']:
form = form.replace(characters, '')
if '-' not in amplitude:
amplitude = ' ' + amplitude
new_wave = amplitude + "\t" + form
waveform.append(new_wave)
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,特别是关于如何修复我的替换字符使其逐列而不是逐行.
要解决第一个问题,您需要通过列进行迭代。
如果您压缩列表(通过itertools.zip_longest(),因为它们的长度并不相同),那么您可以按顺序遍历它们并截断结果:
import itertools
cols = list(itertools.zip_longest(*lst, fillvalue=" "))
for i in range(3, 17): # skip negative signs
cols[i] = "".join(cols[i]).replace('-', '*', 1)
cols[i] = "".join(cols[i]).replace('/', '*', 1)
cols[i] = "".join(cols[i]).replace('\\', '*', 1)
fixed = map("".join, zip(*cols[:17])) # no need to zip longest
for l in fixed:
print(l)
Run Code Online (Sandbox Code Playgroud)
请参阅repl.it上的工作示例,其输出:
3 ***
2 * *
1 * *
0 *** *
-1 *
-2 *
-3
Run Code Online (Sandbox Code Playgroud)
请注意,它确实会用空格填充列表,因此如果它不只是用于打印,您可能需要.strip()结果。将其调整为您的分数输入,我将由您决定。
另一种选择可能更清楚:
def convert_and_truncate(lst, cutoff):
result = []
for str in lst:
str = str[0] + str[1:].replace('-', '*') # skip the negative signs
str = str.replace('/', '*')
str = str.replace('\\', '*')
result.append(str[:cutoff]) # truncate
return result
Run Code Online (Sandbox Code Playgroud)
因为我们要截断列表的其余部分,所以替换是否更改所有内容并不重要。
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |