Python 有没有一种方法可以将变量添加到列表并对其进行排序,但保持列表在相同的范围内?
Python 有没有一种方法可以将变量添加到列表并对其进行排序,但保持列表在相同的范围内?,python,python-3.x,list,sorting,Python,Python 3.x,List,Sorting,list=[3,3,4,6,7]在我的例子中,这个列表已经是有序的了。 新值=5 如何将5放在4和6之间,但将另一个3踢出,这样列表就是[3,4,5,6,7]?这样,列表的长度将保持为5个值。 非常感谢您的帮助,谢谢 您是否尝试过简单地重新分配相应的索引 lst = [3,3,4,6,7] lst[1], lst[2]= 4, 5 也许是这样的: new_value=5 list = [3,3,4,6,7] #sort the list list=sort(list) if new_v
list=[3,3,4,6,7]
在我的例子中,这个列表已经是有序的了。
新值=5
如何将5
放在4
和6
之间,但将另一个3
踢出,这样列表就是[3,4,5,6,7]
?这样,列表的长度将保持为5个值。
非常感谢您的帮助,谢谢 您是否尝试过简单地重新分配相应的索引
lst = [3,3,4,6,7]
lst[1], lst[2]= 4, 5
也许是这样的:
new_value=5
list = [3,3,4,6,7]
#sort the list
list=sort(list)
if new_value<= list[0]:
#add new value at the beginning of list and remove the last element of list
list.append(i)
list=list[:-1]
if new_value>list[0] and new_value<list[-1]:
#add new value at the beginning of list, re-sort the list and remove the first (or last) element of list
list.append(i)
list=sort(list)
list=list[1:] #remove the first element
#or to remove the last element
# list=list[:-1]
if new_value>=list[-1]:
#add new value at the beginning of list, re-sort the list and remove the first element of list
list.append(i)
list=sort(list)
list=list[1:]
new_值=5
列表=[3,3,4,6,7]
#对列表排序
列表=排序(列表)
如果新值列表[0]和新值=列表[-1]:
#在列表的开头添加新值,重新排序列表并删除列表的第一个元素
列表.附加(i)
列表=排序(列表)
列表=列表[1:]
我不确定你什么时候决定放弃哪个值,这就是你想要的吗?
排序后,这将始终返回新列表的最后5项
list = [3,3,4,6,7]
list.append(5)
newList = [item for item in sorted(list)][-5:]
>> [3, 4, 5, 6, 7]
你如何决定剔除哪个值?