我有一个经常更改的动态整数列表,我希望能够在列表中找到下一个最高的出现次数。这是我目前列表的输出:
[u'4', u'32', u'72', u'100']
我写了一篇很长的if else声明,以确认我的思维/方法是否有效。我现在希望能够用for循环替换if else语句(我认为for循环应该是最好的),但是我在编写for循环时遇到了很多问题。
如何使用for循环替换以下if else语句?
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
另外,我列表中每个值之前的u代表什么(u' 4')?
感谢。
答案 0 :(得分:1)
有三个步骤:
以下是三个步骤:
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
您可以将它们组合在一个表达式中:
next_highest = max(map(int, resume_menu_list01))+1
next_highest = max(map(int, resume_menu_list01))+1
将返回最大值 数字加一,不在列表中。如果我有4号和 我想找到下一个最高的数字,即32,我该怎么写 for循环?
您是否只想对列表进行排序,以便您可以按照旧订单进行操作?如果是,sorted_list = sorted(resume_menu_list01, key=int)
;但要在现有列表中找到最高值,请使用max
:
>>> i = [u'4', u'32', u'72', u'100']
>>> print(max(map(int, i)))
100
现在,如果您想知道已知值的下一个最高值是什么:
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']))
答案 1 :(得分:0)
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
这是你想要的?否则@Burhan Khalid的答案会更加优化。