Python:虽然,如果,否则计数 [英] Python: While, if, else counting
问题描述
我在使用 while/if 语句时遇到了一些问题.
I'm having a bit of an issue with a while/if statement.
我有一个值列表,通常这些值是字符串,但有时它可以返回 None.这是我的两次尝试:
I have a list of values, normally these values will be strings, but sometimes it can return None. Here are two of my attempts:
x = ['One','Two','Three',None,None]
New = []
count=0
for y in x:
while isinstance(y,str):
New.append(y)
count+=1
break
else:
count+=1
New.append('New - '+str(count))
print New,count
>>> The list repeats several times
New = []
for y in x:
count=0
if y is not None:
New.append(y)
count+=1
else:
count+=1
New.append('New - '+str(count))
>>>['One','Two','Three','New - 1','New - 1']
我希望输出是:['One','Two','Three', 'New - 4', 'New - 5'],如果 None 值在中间,则保持列表的顺序.
I would like the output to be: ['One','Two','Three', 'New - 4', 'New - 5'], and to keep the ordering of the list if the None value was somewhere in the middle.
我不确定我哪里出错了,两者都相差甚远.对不起,如果这很简单,我还在学习.我在这个论坛上找了一个类似的问题,有些人有帮助,但我还是想不通.
I'm not sure where I'm going wrong, neither of them are far off. Sorry if this is quite simple i'm still learning. I've looked around this forum for a similar query, some have helped but i still can;t figure it out.
推荐答案
每当计算索引和循环列表时,最好使用 enumerate
.如果您不希望它从默认的 0
开始,您也可以指定一个起始编号.这里似乎就是这种情况,因为您似乎想从 1
Whenever counting the index and looping over a list, it's best to use enumerate
. You can also specify a start number if you don't want it to start from 0
which is the default. That seems to be the case here, since you appear to want to count starting from 1
还有 while
循环似乎毫无意义.一个简单的 if
就足够了.如果您知道项目将是 None
,那么检查它是否是 None
可能比检查 isinstance(item, str)
Also the while
loop seems pointless. A simple if
would be sufficient. And if you know the items will be None
it's probably better to check if it's None
rather than checking isinstance(item, str)
所以我相信您正在寻找的解决方案类似于
So I believe the solution you're looking for goes something like
x = ['One', 'Two', 'Three', None, None]
new = []
for index, item in enumerate(x, start=1):
if item is None:
new.append('New - {}'.format(index))
else:
new.append(item)
print(new)
这应该会产生预期的结果.如果你愿意,这也可以写成列表理解.
This should produce the result that is expected. This could also be written as a list comprehension, if you like.
new = [item if item is not None else 'New - {}'.format(index) for index, item in enumerate(x, start=1)]
输出为
['One', 'Two', 'Three', 'New - 4', 'New - 5']
这篇关于Python:虽然,如果,否则计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!