简体   繁体   English

如何从字典内的随机列表中选择随机项目

[英]How to pick random item from random list inside a dictionary

So I am having trouble with getting random item from random list inside a dictionary.所以我在从字典中的随机列表中获取随机项目时遇到了麻烦。 The code I have right now我现在拥有的代码

tasktotal = ["Medbay/Submit Scan","Medbay/Submit Example","Cafeteria/Connect Wire","Electrical/Connect Wire","Cafeteria/Empty Garbage","Security/Connect Wire","Navigation/Navigate","Upper Engine/Fuel","Lower Engine/Fuel","Shield/Prime Shield","Storage/Empty Garbage","Admin/Swipe Card","Weapon/Clear Asteroid","Admin/Connect Wire","Storage/Connect Wire"]

And then I did然后我做了

task = dict(s.split('/') for s in task)

The problem with this is that I can only have one task in one location.这样做的问题是我只能在一个位置执行一项任务。 I want to make it list in dictionary and also pick a random task from random location.我想在字典中列出它,并从随机位置选择一个随机任务。

You can make a dictionary that maps keys to lists like this (alternatively you can use a defaultDict ):您可以制作一个字典,将键映射到这样的列表(或者您可以使用defaultDict ):

tasktotal = ["Medbay/Submit Scan","Medbay/Submit Example","Cafeteria/Connect Wire","Electrical/Connect Wire","Cafeteria/Empty Garbage","Security/Connect Wire","Navigation/Navigate","Upper Engine/Fuel","Lower Engine/Fuel","Shield/Prime Shield","Storage/Empty Garbage","Admin/Swipe Card","Weapon/Clear Asteroid","Admin/Connect Wire","Storage/Connect Wire"]

d = {}
for k, v in (s.split('/') for s in tasktotal):
    d.setdefault(k, []).append(v)

this will make d look like:这将使d看起来像:

{'Medbay': ['Submit Scan', 'Submit Example'],
 'Cafeteria': ['Connect Wire', 'Empty Garbage'],
 'Electrical': ['Connect Wire'],
 'Security': ['Connect Wire'],
 'Navigation': ['Navigate'],
 'Upper Engine': ['Fuel'],
 'Lower Engine': ['Fuel'],
 'Shield': ['Prime Shield'],
 'Storage': ['Empty Garbage', 'Connect Wire'],
 'Admin': ['Swipe Card', 'Connect Wire'],
 'Weapon': ['Clear Asteroid']}

Given that you can get a random value from any list you like:鉴于您可以从您喜欢的任何列表中获取随机值:

import random

random.choice(d['Medbay'])
# 'Submit Example' (or 'Submit Scan')

First you need to create a dictionary.首先你需要创建一个字典。 Keys are unique, if you want to store multiple values under one key, store a list as value.键是唯一的,如果要在一个键下存储多个值,请将列表存储为值。 Then draw from it:然后从中抽取:

tasktotal = ["Medbay/Submit Scan","Medbay/Submit Example","Cafeteria/Connect Wire",
             "Electrical/Connect Wire","Cafeteria/Empty Garbage",
             "Security/Connect Wire","Navigation/Navigate",
             "Upper Engine/Fuel","Lower Engine/Fuel","Shield/Prime Shield",
             "Storage/Empty Garbage","Admin/Swipe Card","Weapon/Clear Asteroid",
             "Admin/Connect Wire","Storage/Connect Wire"]

# import defaultdict
# d = defaultdict(list) 
# instead of d={} and then simply use d[key].append(...) it creates
# the list itself

data = {}
for task in tasktotal:
    key, value = task.split("/") 
    # either use plain dict and test key yourself
    if key in data:
        data[key].append(value)
    else:
        data[key] = [value]

    # or use setdefault 
    # d.setdefault(key,[]).append(value)

    # or  
    # d[key].append(...) with defaultdict(list)

print(data)

Then query randomly:然后随机查询:

import random
# random key/value-list pair
key,values = random.choice(list(data.items()))
# random item from value-list
print(key, "->",  random.choice(values)) 

Output:输出:

'edbay': ['Submit Scan', 'Submit Example'], 
'Cafeteria': ['Connect Wire', 'Empty Garbage'], 
'Electrical': ['Connect Wire'], 'Security': ['Connect Wire'], 
'Navigation': ['Navigate'], 'Upper Engine': ['Fuel'], 
'Lower Engine': ['Fuel'], 'Shield': ['Prime Shield'], 
'Storage': ['Empty Garbage', 'Connect Wire'], 
'Admin': ['Swipe Card', 'Connect Wire'], 'Weapon': ['Clear Asteroid']}


Lower Engine -> Fuel

You could have combined answers to these 2 questions to selfanswer yours:你可以结合这两个问题的答案来自我回答你的问题:

You could use itertools.groupby你可以使用itertools.groupby

Note that the iterable you feed to groupby should be sorted on the same key you use for grouping, but in your case that is a simple sort…请注意,您提供给groupby的可迭代对象应该按照您用于分组的相同键进行排序,但在您的情况下,这是一个简单的排序......

In [12]: from itertools import groupby 
    ...: data = ["Medbay/Submit Scan","Medbay/Submit Example","Cafeteria/Connect Wire","Electrical/Connect Wire","Cafeteria/Empty Garbage","Security/Connect Wire","Navigation/Navigate","Upper Engine/Fuel","Lower Engine/Fuel","Shield/Prime Shield","Storage/Empty Garbage","Admin/Swipe Card","Weapon/Clear Asteroid","Admin/Connect Wire","Storage/Connect Wire"] 
    ...: data.sort() 
    ...: {k:list(s[1] for s in g) 
    ...:     for k, g in groupby((s.split('/') for s in data), lambda s:s[0])}    
Out[12]: 
{'Admin': ['Connect Wire', 'Swipe Card'],
 'Cafeteria': ['Connect Wire', 'Empty Garbage'],
 'Electrical': ['Connect Wire'],
 'Lower Engine': ['Fuel'],
 'Medbay': ['Submit Example', 'Submit Scan'],
 'Navigation': ['Navigate'],
 'Security': ['Connect Wire'],
 'Shield': ['Prime Shield'],
 'Storage': ['Connect Wire', 'Empty Garbage'],
 'Upper Engine': ['Fuel'],
 'Weapon': ['Clear Asteroid']}

In [13]: d = _                                                                                             

In [14]: from random import choice                                                                   

In [15]: rk = choice(list(d.keys()))                                                                 

In [16]: rk                                                                                          
Out[16]: 'Lower Engine'

In [17]: choice(d[rk])                                                                               
Out[17]: 'Fuel'

In its way, elegant…以它的方式,优雅……

convert your code to dic to get value by key 

tasktotal = ["Medbay/Submit Scan","Medbay/Submit Example","Cafeteria/Connect 
Wire","Electrical/Connect Wire","Cafeteria/Empty Garbage",
"Security/Connect Wire","Navigation/Navigate","Upper Engine/Fuel","Lower 
Engine/Fuel","Shield/Prime Shield",
"Storage/Empty Garbage","Admin/Swipe Card","Weapon/Clear Asteroid","Admin/Connect 
Wire","Storage/Connect Wire"]

dic = {}
key = 0
for i in tasktotal:
i = i.split('/')
dic[key] = i[0]
key+=1
dic[key] = i[1]
key+=1
print(dic)

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

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