Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在洗牌后获取python列表项的上一个索引值_Python - Fatal编程技术网

在洗牌后获取python列表项的上一个索引值

在洗牌后获取python列表项的上一个索引值,python,Python,假设我有这样一个python列表: l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 通过使用random.shuffle >>> import random >>> random.shuffle(l) >>> l [5, 3, 2, 0, 8, 7, 9, 6, 4, 1] 我有上面的清单 如何获得无序列表中每个项的上一个索引值列表 如果您的值是唯一的,只需使用list.index方法即可。例如,您可以执行以下操作:

假设我有这样一个python列表:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
通过使用random.shuffle

>>> import random
>>> random.shuffle(l)
>>> l
[5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
我有上面的清单


如何获得无序列表中每个项的上一个索引值列表

如果您的值是唯一的,只需使用
list.index
方法即可。例如,您可以执行以下操作:

import random
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
start_l = l[:]
random.shuffle(l)
for elem in l:
    print(elem, '->', start_l.index(elem))
当然,在您的示例中,这很简单-每个元素都已经是它的初始索引

# gives the same result as above.
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(l)
for elem in l:
    print(elem, '->', elem)
事实上,最好的方法很大程度上取决于你想做什么。如果您有其他数据,可能最简单的方法是只洗牌索引,而不是数据。这避免了任何重复等问题。基本上,您会得到一个排列列表,其中每个元素都是位置移动到的索引。例如,
[2,1,0]
是用于反转列表的排列

l = list(random.randint(0, 10) for _ in range(10))
l_idx = list(range(len(l)))  # list of indices in l
random.shuffle(l_idx)
for new_idx, old_idx in enumerate(l_idx):
    print(l[old_idx], '@', old_idx, '->', new_idx)

您可以使用
枚举
将每个项与其索引配对,然后将其洗牌

>>> import random
>>> l = [4, 8, 15, 16, 23, 42]
>>> x = list(enumerate(l))
>>> random.shuffle(x)
>>> indices, l = zip(*x)
>>> l
(4, 8, 15, 23, 42, 16)
>>> indices
(0, 1, 2, 4, 5, 3)

这种方法的一个优点是,无论
l
是否包含重复项,它都可以工作。

要使用字典跟踪所有内容,可以执行以下操作:

在字典理解中使用
枚举
,在迭代中使用索引和值,然后将值指定为键,将索引指定为值

import random

l = [5, 3, 2, 0, 8, 7, 9, 6, 4, 1]
d = {v: i for i, v in enumerate(l)}
print(d) # current state
random.shuffle(l)
这里的优点是,您可以获得
O(1)
lookup来检索您正在查找的任何值的索引


但是,如果您的列表包含重复项,则应参考Kevin的答案。

创建原始
列表的副本,并将副本混洗:

>>> import random    
>>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l_copy = list(l)  # <-- Creating copy of the list
>>> random.shuffle(l_copy)  # <-- Shuffling the copy
>>> l_copy   # <-- Shuffled copy               
[8, 7, 1, 3, 6, 5, 9, 2, 0, 4]
>>> l   # <-- original list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 
>>随机导入
>>>l=[0,1,2,3,4,5,6,7,8,9]
>>>l#u copy=list(l)#>>random.shuffle(l#u copy)#>>l#>>l#>>

比其他答案更直观的选择:


洗牌一系列索引,并使用它来获得原始值的洗牌列表。

在每次调用ShuffledJaw后,使用字典跟踪每个数字的索引,你能给我举个例子吗?你真的需要洗牌列表还是只洗牌索引?