首页 > 解决方案 > 需要遍历两个列表并吐出最终列表,但能够从其中一个列表的任何元素开始

问题描述

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 中选择一个随机起始元素,然后将其与从元素 0 开始的列表 1 的每个元素进行比较。如果元素为真,则从列表 2 中吐出相应的元素值。

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

标签: pythonlistloopsformat

解决方案


我解决这个问题的方法是:

  • 从用户输入读取的列表 2 左移 N 个位置。

- 遍历列表 1,如果值为真,则将列表 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)

推荐阅读