Python嵌套的IF语句未遍历整个列表

时间:2018-10-30 17:16:34

标签: python-3.x list if-statement nested-loops

我需要一些帮助来理解为什么它没有遍历完整列表以及如何纠正此问题。我需要替换列表B和列表A之间的某些值以执行其他过程。该代码应该给了我

的最终列表
b = ['Sick', "Mid 1", "off", "Night", "Sick", "Morning", "Night"] 

我正在考虑2个嵌套的IF语句,因为它正在评估2种不同的东西。我的代码给了我

['Sick', 'Mid 1', 'off', 'Night', 'off', 'Morning', 'Night']

在元素[0]上正确,但在元素[4]上正确。
我在玩i = i+1

的缩进
a = ['Sick', 'PR', '', 'PR', 'Sick', 'PR', 'PR']
b = ["off", "Mid 1", "off", "Night", "off", "Morning", "Night"]

i = 0
for x in the_list:
    for y in see_drop_down_list:
        if x =="off":
            if y == "":
                the_list[i] = "off"

            else:
                the_list[i]=see_drop_down_list[i]
i = i + 1           
print (the_list)

1 个答案:

答案 0 :(得分:2)

您无需在此处进行两次迭代。更正的代码:

a = ['Sick', 'PR', '', 'PR', 'Sick', 'PR', 'PR']
b = ['off', 'Mid 1', 'off', 'Night', 'off', 'Morning', 'Night']

for i in range(len(b)):  # loop through all indexes of elements in "b"
    if b[i] == 'off' and a[i]:   # replace element, if it's "off" and corresponding element in "a" is not empty
        b[i] = a[i]

print(b)

输出:

  

[“病”,“中1”,“关”,“夜”,“病”,“早晨”,“夜”]