在此代码块中,我尝试从列表中采样两个值,并将它们添加到共享相同键/值结构的两个嵌套字典的每一个中的特定键/值对。我已发表评论以澄清自己的意图。
gym_list = ['reddit.com','amazon.com','twitter.com','linkedin.com','ebay.com','netflix.com','stackoverflow.com','github.com','quora.com','google.com']
for i in range(poke_players[['player_1']['gyms_visited']],poke_players[['player_2']['gyms_visited']]):
if poke_players[['player_1']['gyms_visited']] : None; #If first key/value pair has no value
poke_players[['player_1']['gyms_visited']].append([sample(gym_list,2)]); #add random sample to first key/value pair
else:
poke_players[['player_2']['gyms_visited']] : None; #If second key/value pair has no value
poke_players[['player_1']['gyms_visited']].append([sample(gym_list,2)]): #add random sample to second key/value pair
return poke_players #return the updated dictionary
答案 0 :(得分:0)
您的主要问题似乎是您没有编写有效的Python语法。
我可以看到几种解决您描述的问题的方法。让我们首先将其作为嵌套字典进行处理,使其中一个成为defaultdict
集合。这不是代码的确切实现,而是显示如何创建和操作数据结构的近似值:
from random import sample
from collections import defaultdict
gym_list = ['reddit.com', 'amazon.com', 'twitter.com', 'linkedin.com', 'ebay.com', 'netflix.com', 'stackoverflow.com', 'github.com', 'quora.com', 'google.com']
poke_players = defaultdict(dict)
def initialize_poke_players():
if 'gyms_visited' not in poke_players['player_1']: # If first key/value pair has no value
poke_players['player_1']['gyms_visited'] = sample(gym_list, 2) # add random sample to first key/value pair
if 'gyms_visited' not in poke_players['player_2']: # If second key/value pair has no value
poke_players['player_2']['gyms_visited'] = sample(gym_list, 2) # add random sample to second key/value pair
initialize_poke_players()
print("Player 1:", poke_players['player_1']['gyms_visited'])
print("Player 2:", poke_players['player_2']['gyms_visited'])
输出
> python3 test.py
Player 1: ['twitter.com', 'google.com']
Player 2: ['reddit.com', 'linkedin.com']
>
一种更简单的单字典方法是由字符串元组组成的复合键:
from random import sample
gym_list = ['reddit.com', 'amazon.com', 'twitter.com', 'linkedin.com', 'ebay.com', 'netflix.com', 'stackoverflow.com', 'github.com', 'quora.com', 'google.com']
poke_players = {}
def initialize_poke_players():
if ('player_1', 'gyms_visited') not in poke_players: # If first key/value pair has no value
poke_players[('player_1', 'gyms_visited')] = sample(gym_list, 2) # add random sample to first key/value pair
if ('player_2', 'gyms_visited') not in poke_players: # If second key/value pair has no value
poke_players[('player_2', 'gyms_visited')] = sample(gym_list, 2) # add random sample to second key/value pair
initialize_poke_players()
print("Player 1:", poke_players[('player_1', 'gyms_visited')])
print("Player 2:", poke_players[('player_2', 'gyms_visited')])