![](/img/trans.png)
[英]Python - How to get value of a key from position of dictionary inside a list
[英]Get a random value from a list and its position at the same time in Python
我想知道 Python 中是否有一種方法可以同時從列表中獲取它的隨機值及其位置。
我知道我可以通過兩個步驟來做到這一點:
list_index = random.randrange(len(my_list))
list_value = my_list[index]
另外我想排除 list 中是否有 0 值。 我不能使用 random() 1st 來獲取位置,因為這樣我需要遞歸調用 random() 直到我沒有得到 0。
另一種可能性是調用 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
我該如何實施? 可行嗎? 我一直在網上思考和搜索,但找不到任何東西。
真的提前謝謝你。
亞歷克斯
在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)
輸出:
pos: 2 itemvalue: 6
使用python 3.8,您可以使用walrus 運算符,這使其適用於任何長度的列表:
data = [3, 5, 6, 8, 5, 7]
import random
print("pos:", p := random.choice(range(len(data))), "itemvalue:", data[p])
輸出:
pos: 0 itemvalue: 3
第一個變體從包含位置和值的元組中選擇 - 第二個變體選擇列表中的隨機索引並訪問該位置的列表以獲取值。
您從輸入列表中獲得隨機值 - 為了避免零,您可以循環直到獲得非零值:
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)
輸出:
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
你的問題對我來說不是很清楚,但據我所知,你的想法應該沒問題,應該可以正常工作。
調用 my_list.index(5) 時,您將獲得第一個 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!')
結果
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
如您所見,您的方法為列表中的數字 5 獲取索引 1 和索引 5。
好吧,您可以使用過濾器功能來做您想做的事。
res_list = list(filter(lambda x: my_list[x] == random_value, range(len(my_list))))
上面的代碼 res_list 存儲一個包含索引的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.