简体   繁体   中英

How to randomly sample from python values in a list?

I have a list of stock ticker symbols as values and their sectors as keys in a python defauldict . I would like to randomly sample one or two from each value and place them in their own list, then do some stuff, then randomly sample again and do this for 50 or 100 times.

Is this possible?

Here is the sample of the dictionary.

sector_dict = defaultdict(list,
                          {'Technology': ['AAPL', 'ADBE', 'AMD', 'AMAT', 'FSLR', 'GPRO', 'IBM', 'MSFT', 'MU',
                                          'QCOM', 'TXN', 'XLNX', 'CRM'],
                           'Healthcare': ['ABT', 'GILD', 'MDT', 'BMY'],
                           'Consumer Cyclical': ['AMZN', 'ANF', 'BABA', 'BBY', 'BZUN', 'CMG', 'EBAY', 'GM', 'HD',
                                                 'JD', 'LULU', 'MCD', 'NKE', 'TSLA', 'UA', 'GME'],
                           'Energy': ['APA', 'HAL', 'PBR', 'SLB', 'CVX'],
                           'Industrials': ['BA', 'CAT', 'DE', 'FDX', 'HON', 'UAL'],
                           'Communication Services': ['BIDU', 'FB', 'GOOG', 'NFLX', 'SNAP', 'TWTR', 'ZM', 'CMCSA'],
                           'Real Estate': ['BRX', 'SPG'],
                           'Consumer Defensive': ['COST'],
                           'Basic Materials': ['FCX', 'NEM', 'CLF'],
                           'Financial Services': ['GS', 'HIG', 'LYG', 'MA', 'V', 'C', 'JPM', 'MS']})

Replacement can be True . The only constraint is at least one ticker from each key should be chosen. How do I do this?

When I try, I get a list of lists when all I'm trying to get is a list of values (tickers).

Here was my attempt:

import random
random_port = []
for key, val in sector_dict.items():
    random_port.append(random.sample(val, 1))
random_port

Try:

random_port = []
for value in sector_dict.values():
    random_port += random.sample(value, min(len(value), 2))

Here below I slightly modified your code to select one or two stocks from each category:

import random

random_list = []

for key, val in sector_dict.items():
    random_list.extend(random.sample(val, min(len(val), random.randint(1,2))))

print(random_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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