我对with /if的陈述有点不满意。
我有一个值列表,通常这些值将是字符串,但有时它可以返回任何值。以下是我的两次尝试:
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']我希望输出是:“1”、“2”、“3”、“New-4”、“New-5”,如果没有值在中间,则保持列表的顺序。
我不知道我哪里出了问题,他们俩都很远。抱歉,如果这很简单的话,我还在学习。我已经在这个论坛上寻找了一个类似的查询,有些已经有所帮助,但我仍然找不出答案。
发布于 2017-10-24 16:20:40
每当计数索引和遍历列表时,最好使用enumerate。如果不希望从0开始,您也可以指定一个开始号,这是默认的。这里似乎就是这样,因为您似乎希望从1开始计算
此外,while循环似乎毫无意义。一个简单的if就足够了。如果您知道这些项目将是None,那么最好检查它是否是None,而不是检查isinstance(item, str)
所以我相信你要找的解决方案是
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)这将产生预期的结果。如果你愿意的话,这也可以写成一个清单理解。
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']发布于 2017-10-24 16:23:30
第一个代码:
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:
.
.
.发布于 2017-10-24 16:36:43
代码中有一些语义错误。
https://stackoverflow.com/questions/46915245
复制相似问题