Reputation: 3695
I have a dynamic list of integers that often changes and I want to be able to find the next highest occurance in the list. This is the output of my list at the moment:
[u'4', u'32', u'72', u'100']
I have written a very long if else statement to confirm that my thinking/approach does work. I now want to be able to replace the if else statement with a for loop (i think a for loop should be best here), but I am having many problems in writing the for loop.
How do I replace the following if else statement with a for loop?
if unicode(new_val_xx) in resume_menu_list01:
if unicode(int(new_val_xx)+1) in resume_menu_list01:
next_page = int(new_val_xx)+1
elif unicode(int(new_val_xx)+2) in resume_menu_list01:
next_page = int(new_val_xx)+2
elif unicode(int(new_val_xx)+3) in resume_menu_list01:
next_page = int(new_val_xx)+3
elif unicode(int(new_val_xx)+4) in resume_menu_list01:
next_page = int(new_val_xx)+4
elif unicode(int(new_val_xx)+5) in resume_menu_list01:
next_page = int(new_val_xx)+5
.....
elif unicode(int(new_val_xx)+97) in resume_menu_list01:
next_page = int(new_val_xx)+97
elif unicode(int(new_val_xx)+98) in resume_menu_list01:
next_page = int(new_val_xx)+98
elif unicode(int(new_val_xx)+99) in resume_menu_list01:
next_page = int(new_val_xx)+99
Also, what does the u before each value in my list represent (u'4')?
Thanks.
Upvotes: 0
Views: 211
Reputation: 174728
There are three steps:
Here are the three steps:
list_of_numbers = map(int, resume_menu_list01)
# if you are using Python3, list_of_numbers = list(map(int, resume_menu_list01))
maximum_number = max(list_of_numbers)
next_highest = maximum_number + 1
You can combine them all in one expression:
next_highest = max(map(int, resume_menu_list01))+1
next_highest = max(map(int, resume_menu_list01))+1
will return the max number plus one, which is not in the list. If I have the number 4 and I want to find the next highest number, which is 32, how would I write the for loop?
Do you just want to sort the list so you can step through it in acending order? If so, sorted_list = sorted(resume_menu_list01, key=int)
; but to find the higest value in the existing list, use max
:
>>> i = [u'4', u'32', u'72', u'100']
>>> print(max(map(int, i)))
100
Now, if you want to know what is the next highest value from a known value:
known_value = u'4'
def get_highest(value, items):
sorted_items = sorted(items, key=int)
if sorted_items.index(value) == len(sorted_items) - 1:
# The value is the highest item in the list
# return the item
return value
else:
return sorted_items[sorted_items.index(value)+1]
print(get_highest(known_value, [u'4', u'32', u'72', u'100']))
Upvotes: 1
Reputation: 3447
for new_val_xx in range(1,99):
if unicode(new_val_xx) in resume_menu_list01:
next_page = int(new_val_xx)+new_val_xx
This is what you want? otherwise @Burhan Khalid's answer is more optimized.
Upvotes: 0