Python 需要迭代两个列表并给出最终列表,但能够从其中一个列表的任何元素开始

Python 需要迭代两个列表并给出最终列表,但能够从其中一个列表的任何元素开始,python,list,loops,format,Python,List,Loops,Format,Python中的小问题,第一次发布,寻找一个小项目的帮助 所以我有两个清单: list1=(True,False,True,False,True,True,False,True,False,True,False,True) list2=["A","A#","B","C","C#","D","D#","E","F",&

Python中的小问题,第一次发布,寻找一个小项目的帮助 所以我有两个清单:

list1=(True,False,True,False,True,True,False,True,False,True,False,True)

list2=["A","A#","B","C","C#","D","D#","E","F","F#","G","G#",]
我需要生成第三个列表,这是以下函数的结果:

在列表2中随机选取一个起始元素,然后将其与列表1中从元素0开始的每个元素进行比较。如果元素为true,则从列表2中吐出相应的元素值

举个例子,用户选择list2的元素2(“B”)作为输入,输出应该是(最好不带引号,看到带引号和不带引号的代码会非常棒):
“B”、“C”、“D”、“E”、“F”、“G”、“A”

我相信您在最后的列表中提到
A
D
是有错误的。我想你应该参考
A
D
。无论如何,我认为下面的代码将帮助您

import random
list1=(True,False,True,False,True,True,False,True,False,True,False,True)

list2=["A","A#","B","C","C#","D","D#","E","F","F#","G","G#",]
getRandomElement = list2[random.randrange(0,len(list2))]
finalList = []
if getRandomElement in list2:
    getIndex  = list2.index(getRandomElement)
    for index,value in enumerate(list2):
        if(list1[index]):
            finalList.append(value)

print(finalList)
输出(关于您问题中的当前列表)


我对这个问题的看法是:

  • 按从用户输入读取的N个位置向左移动列表2
-迭代列表1,若值为true,则将列表2的元素I添加到最终列表中

list1=(True,False,True,False,True,True,False,True,False,True,False,True)

list2=["A","A#","B","C","C#","D","D#","E","F","F#","G","G#",]

#user needs to input something to continue
raw_input = input('how many positions?\n')

##shifting the list2 N positions
for i in range(int(raw_input)):
    #we remove the first element in the list and add it back to the end
    element = list2.pop(0)
    list2.append(element)

##Iterating over list 1, and if value is true, add element in index I to a new list.

#creating final list
final = []
for i in range(len(list1)):
    val = list1[i]
    if(val):
        final.append(list2[i])

print(final)

你确定你的输出是正确的吗?我想应该有一个
A
字符,而不是
A 35;
是的,输出是正确的:)这是一个音乐应用程序,其思想是允许用户选择任何开始音符,然后正确和错误的列表构成了爱奥尼亚大音阶的dna。所以本质上你应该能够选择任何开始的音符,然后列表1按照正确的顺序吐出相关的音符。看看@Eddoaso answers,简直完美无瑕。还没有运行它,但只是阅读它看起来像他钉在了头上。pop和N位置移动的漂亮使用哦,天哪!你解决了!这是完美的,这里的技巧是使用N个位置将它们依次“弹出”到列表的末尾,然后嵌套在for循环中的漂亮if语句完美地将其吐出。完美的先生!这是用于音乐应用程序的,因此其背后的逻辑是用户“选择一个起始音符”,元素true和false根据音乐中可用的12个音符中存在的布尔型音符拼写出一个主要的爱奥尼亚音阶:)
list1=(True,False,True,False,True,True,False,True,False,True,False,True)

list2=["A","A#","B","C","C#","D","D#","E","F","F#","G","G#",]

#user needs to input something to continue
raw_input = input('how many positions?\n')

##shifting the list2 N positions
for i in range(int(raw_input)):
    #we remove the first element in the list and add it back to the end
    element = list2.pop(0)
    list2.append(element)

##Iterating over list 1, and if value is true, add element in index I to a new list.

#creating final list
final = []
for i in range(len(list1)):
    val = list1[i]
    if(val):
        final.append(list2[i])

print(final)