从不包含一个特定索引的列表中生成随机索引

2024-04-23 20:00:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个整数列表:l = [1,2,3,4]

对每个元素随机选择一个不同的元素:

for i in range(len(l)):
   idx = # a random index which is NOT equal to i
   # do something with the element at idx

我对Python还是个新手,如果不使用一个循环来生成一个随机索引,并且只在随机数不等于i时停止循环,我无法确定是否有一种方法可以做到这一点。如有任何建议,将不胜感激。在


Tags: toin元素which列表forindexlen
3条回答
l=[1,2,3,4,5]
import random as rd 
def remove_index(list,index):
    res=list[:]
    res.pop(index)
    return res

for i in range(len(l)):
    print rd.choice(remove_index(l,i))

这样做怎么样:在10和{}(本例中,N是列表的长度)之间生成一个随机数,如果这个数等于或大于i,则向该数字添加一个。在

for i in range(len(l)):
    idx = random.randrange(len(l) - 1)
    idx = idx + 1 if idx >= i else idx
    # do stuff with idx

这样,所有在i上滚动的数字都会“向上移动一个”:

^{pr2}$

或者,在一行中,您可以生成一个介于1i + 1N + i之间的数,并取这个数模N,在列表末尾后有效地将其包装起来:

    idx = random.randrange(i + 1, len(l) + i) % len(l)

       0      i          N
before         *****************
after  ******* **********

1)这里的意思是包括下界和排除上界,使用randrange

numpy方法:

import numpy as np

l = np.array([1,2,3,4])
for i in range(len(l)):
    idx = random.choice(np.where(l != l[i])[0])
    # do stuff with idx
    print(i, idx)

输出(显示指数差异):

^{pr2}$

相关问题 更多 >