简体   繁体   English

在 Python 中同时从列表中获取一个随机值及其位置

[英]Get a random value from a list and its position at the same time in Python

I was wondering if there's a way in Python to get from a list, a random value of it and its position at the same time.我想知道 Python 中是否有一种方法可以同时从列表中获取它的随机值及其位置

I know I can do this in two steps:我知道我可以通过两个步骤来做到这一点:

list_index = random.randrange(len(my_list))
list_value = my_list[index]

Also I want to exclude if there's a 0 value inside the list .另外我想排除 list 中是否有 0 值 I can't use random() 1st for getting a position because this way I need to recursively call random() until I don't get a 0.我不能使用 random() 1st 来获取位置,因为这样我需要递归调用 random() 直到我没有得到 0。

Another posibility is to call random() to get values inside the list and exclude the 0, but with this implementation if, for example, there're two (or more) indentical values, Python outputs me the 1st position:另一种可能性是调用 random() 以获取列表中的值并排除 0,但使用此实现,例如,如果有两个(或更多)相同值,Python 将输出第一个位置:

Example:

    [3 5 6 8 5 0]
    Random's output value = 5
    Position = 1

    But 5 value is also in position 4

How can I implement this?我该如何实施? Is it feasible?可行吗? I've been thinking and searching on the web so much, but couldn't find anything.我一直在网上思考和搜索,但找不到任何东西。

Really thank you in advance.真的提前谢谢你。

Alex亚历克斯

Up to python 3.7 you can use a list of the enumerate() d values of your list - this might break in long lists due to memory consumption:python 3.7 之前,您可以使用列表的enumerate() d 值的列表 - 由于内存消耗,这可能会中断长列表:

data = [3, 5, 6, 8, 5, 7]

import random

pos, item = random.choice(list(enumerate(data)))

print("pos:", pos, "itemvalue:", item)

Output:输出:

pos: 2 itemvalue: 6

With python 3.8 you can use the walrus operator which makes it viable for any-lenght lists:使用python 3.8,您可以使用walrus 运算符,这使其适用于任何长度的列表:

data = [3, 5, 6, 8, 5, 7]

import random 
print("pos:", p := random.choice(range(len(data))), "itemvalue:", data[p]) 

Output:输出:

pos: 0 itemvalue: 3

The 1st variant chooses from tuples that contains the position and the value - the 2nd variant chooses a random index into the list and acceses the liston that position to get the value.第一个变体从包含位置和值的元组中选择 - 第二个变体选择列表中的随机索引并访问该位置的列表以获取值。


You get random values from your input list - to avoid zeros you can loop until you get a non-zero value:您从输入列表中获得随机值 - 为了避免零,您可以循环直到获得非零值:

data = [0, 0, 5, 0, 0, 5, 0, 0, 5]

import random

for _ in range(10):
    item = 0
    while item == 0:
        pos, item = random.choice(list(enumerate(data)))
        # pos, item = (p := random.choice(range(len(data))), data[p]) 
    print("pos:", pos, "itemvalue:", item)

Output:输出:

pos: 8 itemvalue: 5     
pos: 8 itemvalue: 5
pos: 5 itemvalue: 5
pos: 8 itemvalue: 5
pos: 2 itemvalue: 5
pos: 5 itemvalue: 5
pos: 2 itemvalue: 5
pos: 8 itemvalue: 5
pos: 5 itemvalue: 5
pos: 8 itemvalue: 5

Your question is not very clear to me but as I understand it your idea should be oké and should work fine.你的问题对我来说不是很清楚,但据我所知,你的想法应该没问题,应该可以正常工作。

You get the first 5's index when calling my_list.index(5).调用 my_list.index(5) 时,您将获得第一个 5 的索引。 But you don't use this.但是你不用这个。

You get a random index and the value at this index which can also be the second 5.您将获得一个随机索引和该索引处的值,该值也可以是第二个 5。

import random

my_list = [3, 5, 6, 0, 8, 5, 7,]

# example of using index()
print(f"This is the first 5's index {my_list.index(5)}")
print()

for i in range(10):

    random_index = random.randrange(len(my_list))
    value = my_list[random_index]
    if value > 0:
        print(f'At position {random_index} the number is {value}')
    else:
        print(f'     Skipping position {random_index} the number is ZERO!')

Result结果

This is the first 5's index 1

At position 6 the number is 7
At position 6 the number is 7
At position 0 the number is 3
     Skipping position 3 the number is ZERO!
At position 4 the number is 8
At position 1 the number is 5
At position 5 the number is 5
At position 1 the number is 5
At position 1 the number is 5
At position 4 the number is 8

As you can see your method gets index 1 as well as index 5 for the number 5 in the list.如您所见,您的方法为列表中的数字 5 获取索引 1 和索引 5。

Well, you can use filter function for doing that you want.好吧,您可以使用过滤器功能来做您想做的事。

res_list = list(filter(lambda x: my_list[x] == random_value, range(len(my_list)))) 

The code above, res_list stores a list which contains indices.上面的代码 res_list 存储一个包含索引的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM