如果条件存在,我有一个问题就是跳过一些数据
我的循环输出:
None
2 of 61
None
None
None
2 of 1,976
2 of 52
2 of 56
2 of 231
2 of 59
None
2 of 250
2 of 138
2 of 367
None
2 of 221
2 of 372
None
2 of 90
None
2 of 208
但我希望我的循环只打印第一行,如:None, 2 of 61, none, 2of 1,976 and so on :)
我怎样才能实现它?我尝试了一些带有计数器标志的东西,但它仍然打印所有“无”值
if comment.string == None:
flag=+1
if flag==1:
countCC = comment.string
else:
continue
else:
if comment.string.find('of') != -1:
countC = comment.string.split("of ")
countCC = int(re.sub("\D", "", countC[1]))
flag = 0
try:
worksheet.write(row, 4, "Komentarzy:")
worksheet.write(row, 5, countCC)
row += 1
except Exception:
pass
答案 0 :(得分:3)
如果您只想在None
后阻止None
,只需查看上一项:
prev = 'anything but None'
for item in data:
if item is None and prev is None:
continue
print(item)
prev = item
答案 1 :(得分:1)
您可能想要使用continue
。
if your condition that you want to skip:
continue
else:
normal operation
答案 2 :(得分:1)
此解决方案使用一个标志,只要找到(并打印)第一个True
元素,就需要将其设置为None
,以便跳过任何后续的None
元素。非None
元素将重置标志,因此循环可以重复。根据需要进行调整。
data = [
None,
'2 of 61',
None,
None,
None,
'2 of 1,976',
'2 of 52',
'2 of 56',
'2 of 231',
'2 of 59',
None,
'2 of 250',
'2 of 138',
'2 of 367',
None,
'2 of 221',
'2 of 372',
None,
'2 of 90',
None,
'2 of 208',
]
# initialize the flag
skip_next_none = False
for item in data:
# if the current item is None start the checks
if item is None:
# if the flag is set, skip this
if skip_next_none:
continue
# otherwise, set the flag to skip the next
skip_next_none = True
else:
# we found a non-None element: clear the flag
skip_next_none = False
print item
答案 3 :(得分:0)
你也可以使用'计数'变量,以确定是否'无'已经打印过,只打印出它遇到的第一个,然后再继续。
如果这确实符合您的要求,它应该为您节省一些代码。不使用你的变量,不一定是最pythonic但是它的作用是什么:
冲洗/重复:)
count = 0
for comment in comments:
if comment == None and count < 1:
print(comment)
count = 1
elif comment != None:
print(comment)
count = 0