如何使用count变量递增python3? 我想先读取list_r,然后在读取list_r中的第一个元素时,应检查条件,并在增加后转到下一个元素
count = 0
list_r=["1","2","3","4"]
var = "empty"
for i in list_r:
if i == "2":
var = "Done_2"
print(var)
count += 1
我想先读取list_r,然后在读取list_r中的第一个元素时,应检查条件是否成立,并在递增后转到下一个元素
预期结果:
empty
Done_2
empty
empty
答案 0 :(得分:1)
您错过了几点:
print
应该在for
循环中,因为您要为每次迭代打印结果。empty
应该在循环的每次迭代中重置,因为您需要在每次迭代中测试新项目。这是一种方法。
此外,我建议您看看format
函数来格式化显示的string
(here是对该函数的很好解释)。这不会浪费您的时间来查看此功能!
count = 0
v = ["1", "2", "3", "4"]
# Iterate over the list
for i in v:
# Update counter
count += 1
# Set default value of var : empty
var = "empty"
# Update var value according to i value
if i == "1":
var = "Done_1"
if i == "2":
var = "Done_2"
# Print the result
print("Dummy {0}: {1}".format(count, var))
输出:
# Dummy 1: Done_1
# Dummy 2: Done_2
# Dummy 3: empty
# Dummy 4: empty
答案 1 :(得分:0)
您应该添加else语句
for i in v:
if i == "1":
var = "Done_1"
if i == "2":
var = "Done_2"
else:
var = "empty"
答案 2 :(得分:0)
对于当前编辑的问题:
list_r=["1","2","3","4"]
var = "empty"
for i in v:
if i == "2":
var = "Done_2"
else:
var = "empty"
print(var)