可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm having a bit of an issue with a while/if statement.
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']
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.
回答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
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)]
The output is
['One', 'Two', 'Three', 'New - 4', 'New - 5']
回答2:
First code:
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)
Second Code:
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)
In second piece of code initialize count=0 outside the for loop.
In first code you can also replace 'while' with 'if':
.
.
.
if isinstance(y,str):
New.append(y)
count+=1
else:
.
.
.
回答3:
On the line 17
You declaring the count variable inside the loop
That means, that on every iteration
count variable setting to zero
回答4:
You can also try this simple solution
x = ['One','Two','Three',None,None]
for i in range(0,len(x)):
if x[i]==None:
x[i]='New -'+ str(i+1)
print x
回答5:
You have some semantic errors in your code.
First example in the "while" statement you've put an "else"! "else" follows "if" statement and in this iteration you don't need that.
Second code part. You want to increment the count value every time the for statement is executed but you're setting the value to 0 every time. So after each execution of the for loop it again will be set to 1->0->1->0...
So remove the line and put it before starting the for loop.
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))
回答6:
A while loop + unconditional break is quite odd. It will work the same way with if and no break.
回答7:
Another way of resolving this problem is by using the built-in Python function called sorted: here is my example hope it helps
# Support problem on Stackflow answered by Waheed Rafi { Wazzie }
import sys
listOfNames = ['John','Waheed','Foo','Boo']
# print in unorder list
for element in listOfNames:
print(element)
print("--------------------------------------")
print("The new sorted list in Alphabetically")
print("--------------------------------------")
sortedlist = sorted(listOfNames) # python has built-in function call sorted
# print List in order ie alphabetically
for sortedElement in sortedlist:
print(sortedElement)
Please give me give me thumbs up if this has help.