Python: While, if, else counting

2020-05-07 05:57发布

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.

7条回答
男人必须洒脱
2楼-- · 2020-05-07 06:21

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.

查看更多
Explosion°爆炸
3楼-- · 2020-05-07 06:31

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
查看更多
Anthone
4楼-- · 2020-05-07 06:34

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']
查看更多
不美不萌又怎样
5楼-- · 2020-05-07 06:38

You have some semantic errors in your code.

  1. First example in the "while" statement you've put an "else"! "else" follows "if" statement and in this iteration you don't need that.

  2. 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楼-- · 2020-05-07 06:38

A while loop + unconditional break is quite odd. It will work the same way with if and no break.

查看更多
疯言疯语
7楼-- · 2020-05-07 06:42

On the line 17

You declaring the count variable inside the loop That means, that on every iteration count variable setting to zero

查看更多
登录 后发表回答