【问题标题】:How to find item index after selecting randomized item from array从数组中选择随机项目后如何查找项目索引
【发布时间】:2017-03-16 18:01:42
【问题描述】:

试图让我在一个数组中随机化 4 个对象并随机选择其中一个对象来工作。我需要能够取回所选对象的原始索引号。关于我应该如何尽可能短地写这个的任何想法?

arrayRandomSongs = []
arrayChosen = []
trackChosen = ""

def randomizeArray(self):
    del self.arrayRandomSongs[:] # wipes array of all contents without making a new one
    self.arrayRandomSongs = self.arraySongs[:]
    random.shuffle(self.arrayRandomSongs)

def chooseListing(self):
    del self.arrayChosen[:] # same here
    for i in xrange(4):
        self.arrayChosen.append(self.arrayRandomSongs[i])
    del self.arrayRandomSongs[0:3]

def chooseTrack(self):
    self.trackChosen = random.choice(self.arrayChosen)

如您所见,我想为 trackChosen 对象选择 arayChosen 索引号,但由于它是随机的,我不知道该怎么做。

【问题讨论】:

  • 我的意思是我想获取arrayChosen的索引号,而不是原始的原始数组

标签: python arrays python-2.7 random


【解决方案1】:

您必须在随机化之前跟踪索引。然后在随机化并从随机列表中选择一个元素后访问跟踪列表中的索引值。

要获取列表中元素的索引,您可以使用<list>.index(<element>)

说明:

在改组其元素之前创建arrayRandomSongs 的副本。

original_arrayRandomSongs = arrayRandomSongs[:]

通过执行random.choice 获取trackChosen 的值后,使用该值通过执行获取其在原始列表中的索引

original_arrayRandomSongs.index(self.trackChosen)

【讨论】:

  • 我看到有人支持你的帖子,唉,我不太明白这里在说什么......
【解决方案2】:

你可以这样做

list = [4,1,3,2]
list_with_indices = [(num,i) for i, num in enumerate(list)]
shuffle(list_with_indices)

基本上你会跟踪原始索引。

【讨论】:

  • 随机播放功能是如何获得的?
  • from random import shuffle
猜你喜欢
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
相关资源
最近更新 更多