我的python代码中有两个列表:list_1 = [1,'是',3,'否',5,'是',7]和list_2 = ['a','b','c']
我想将list_2的值插入到list_1的“是”或“否”。
我已经通过获取list_1的索引值并尝试插入list_2进行了类似的尝试,但是没有用。
list_1 = [1, 'Yes', 3, 'No', 5, 'yes', 7]
list_2 = ['a', 'b', 'c']
for (each, i) in zip(list_2, range(len(list_1))):
if list_1 == 'yes' or list_1 == 'no':
list_1.insert(i, each)
for each in list_1:
print(each)
我只得到list_1的输出,我想要像这样的最终列表f_list = [1,'a',3,'b',5,'c',7]如何实现呢?
在你目前的做法,你的清单,比较yes
,并no
在有条件的if list_1 == 'yes' or list_1 == 'no':
这是行不通的,因此如果条件永远不会满足,并list_1
保持原样
使用for循环是寻找一种简单的方法yes
,并no
在list_1
,一旦发现,用的元素替换它list_2
,并增加一个计数器去的下一个元素list_2
list_1 = [1, 'Yes', 3, 'No', 5, 'yes', 7]
list_2 = ['a', 'b', 'c']
#variable to keep track of elements of list_2
index = 0
#Iterate through indexes and item of list_1 using enumerate
for idx, item in enumerate(list_1):
#If an item in list_1 matches yes or no
if str(item).lower() in ['yes', 'no']:
#Replace that item with item in list_2
list_1[idx] = list_2[index]
#Move to next item in list_2
index+=1
print(list_1)
输出将是
[1, 'a', 3, 'b', 5, 'c', 7]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句