簡體   English   中英

在列表中的每個項目(字符串)之前添加整數

[英]Adding ints before each item(strings) in list

如果我在 Python 中有一個列表,例如:

Notes = ["F5","G5","B5"]

那么我將如何在每個項目之前添加一個不斷增長的數字?
所以輸出看起來像這樣:

magic

print(newlist)

#2, F5, 4, G5, 6, B5

例如,我嘗試過的是:

midi = ["F5","G5","C5"]
for m in midi:

    output = (note.Note(m))

    n1 = note.Note('G', type='half')
    st4 = stream.Stream()
    st4.append(n1)

    for n in output:
        p += 2

        print( p, output)

    st4.insert(output)
    print(st4)

這給了我錯誤:

對象不可迭代

您可以使用 for 循環 for i from 2 to 2 * (len_of_list + 1)以等於 2 的步長來實現此目的。然后,在索引i - 2處插入值i

notes = ["F5", "G5", "B5"] # notes list
newlist = notes # copy original list

 # for loop starting at 2 and stopping at 7 from 2 to 6 given that step = 2
for i in range(2, 2 * (len(notes) + 1), 2):
    newlist.insert(i - 2, i) # insert value i (2, 4, 6) at index i - 2 (0, 2, 4)

# prints result
print(", ".join(str(value) for value in newlist))

輸出:
2、F5、4、G5、6、B5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM