在 Python 中移动列表的最佳方式?
Best way to shift a list in Python?
我有一个数字列表,比方说:
my_list = [2, 4, 3, 8, 1, 1]
从这个列表中,我想获得一个新的列表。该列表将从最大值开始直到结束,我希望添加第一部分(从开始到最大值之前),如下所示:
my_new_list = [8, 1, 1, 2, 4, 3]
(基本上对应一个横图移位...)
有简单的方法吗? :)
这样的事情怎么样:
max_idx = my_list.index(max(my_list))
my_new_list = my_list[max_idx:] + my_list[0:max_idx]
想申请多少就申请多少,
左边:
my_list.append(my_list.pop(0))
右边:
my_list.insert(0, my_list.pop())
或者您可以执行以下操作,
def shift(l,n):
return itertools.islice(itertools.cycle(l),n,n+len(l))
my_list = [2, 4, 3, 8, 1, 1]
list(shift(my_list, 3))
详细说明 Yasc 移动列表值顺序的解决方案,这是一种将列表从最大值开始的方法:
# Find the max value:
max_value = max(my_list)
# Move the last value from the end to the beginning,
# until the max value is the first value:
while my_list[0] != max_value:
my_list.insert(0, my_list.pop())
我有一个数字列表,比方说:
my_list = [2, 4, 3, 8, 1, 1]
从这个列表中,我想获得一个新的列表。该列表将从最大值开始直到结束,我希望添加第一部分(从开始到最大值之前),如下所示:
my_new_list = [8, 1, 1, 2, 4, 3]
(基本上对应一个横图移位...)
有简单的方法吗? :)
这样的事情怎么样:
max_idx = my_list.index(max(my_list))
my_new_list = my_list[max_idx:] + my_list[0:max_idx]
想申请多少就申请多少,
左边:
my_list.append(my_list.pop(0))
右边:
my_list.insert(0, my_list.pop())
或者您可以执行以下操作,
def shift(l,n):
return itertools.islice(itertools.cycle(l),n,n+len(l))
my_list = [2, 4, 3, 8, 1, 1]
list(shift(my_list, 3))
详细说明 Yasc 移动列表值顺序的解决方案,这是一种将列表从最大值开始的方法:
# Find the max value:
max_value = max(my_list)
# Move the last value from the end to the beginning,
# until the max value is the first value:
while my_list[0] != max_value:
my_list.insert(0, my_list.pop())