【问题标题】:Python nested IF statement not iterating the entire listPython嵌套的IF语句没有迭代整个列表
【发布时间】:2018-10-30 17:16:33
【问题描述】:

我需要一些帮助来理解为什么它没有迭代完整列表以及如何纠正这个问题。我需要替换列表 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)

【问题讨论】:

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


    【解决方案1】:

    您不需要在这里进行双重迭代。更正代码:

    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)
    

    输出:

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

    【讨论】:

    • 非常感谢您的帮助。这些 for 循环总是让我感到困惑。
    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多