Python 嵌套 IF 语句未迭代整个列表
Python nested IF statement not iterating the entire list
我需要一些帮助来理解为什么它没有迭代完整列表以及如何更正它。我需要替换列表 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)
你不需要在这里做双重迭代。更正后的代码:
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']
我需要一些帮助来理解为什么它没有迭代完整列表以及如何更正它。我需要替换列表 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)
你不需要在这里做双重迭代。更正后的代码:
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']