Python:While、if、else 计数

2024-03-08

我对 while/if 语句有一些疑问。

我有一个值列表,通常这些值是字符串,但有时它可以返回 None 。这是我的两个尝试:

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 值位于中间的某个位置,则保持列表的顺序。

我不知道我错在哪里,两者都相差不远。抱歉,如果这很简单,我仍在学习。我在这个论坛上查找了类似的查询,有些有所帮助,但我仍然无法弄清楚。


第一个代码:

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)

第二个代码:

x = ['One','Two','Three',None,None]
New = []
count=0
for y in x:
    if y is not None:
        New.append(y)
        count+=1
    else:
        count+=1
        New.append('New - '+str(count))
print (New,count)

在第二段代码中,在 for 循环之外初始化 count=0。

在第一个代码中,您还可以将“while”替换为“if”:

.
.
.    
if isinstance(y,str):
    New.append(y)
    count+=1
else:
.
.
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:While、if、else 计数 的相关文章

随机推荐