python - 需要遍历两个列表并吐出最终列表,但能够从其中一个列表的任何元素开始
问题描述
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#"
解决方案
我解决这个问题的方法是:
- 从用户输入读取的列表 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)
推荐阅读
- mysql - InnoDB:忽略空间 ID 为 26146 的数据文件“./catalog_category_product_index_store1.ibd”,因为重做日志引用
- python - 使用 Pycharm 执行不以关键字“test”开头的文件的 Pytest
- typescript - 使用 SuppressImplicitAnyIndexErrors = true 抑制 TypeScript 中的括号语法
- ruby-on-rails - Ruby on Rails - 参数化
- javascript - 如何使用来自另一个对等方的 WebRTC 连接添加视频流?
- python - python:具有可变函数名称的装饰器
- multithreading - 并行执行比顺序执行慢,即使代码“很重”
- python - 使用适当的 NaN 处理将熊猫数据框列从数字转换为字符串
- iphone - 如何在 iOS 模拟器上使用 appium 对 Google 移动应用程序进行自动化测试?
- excel - 在列和行中具有两个不同标准的 SUM