从Python中的列表字典中选择随机项

时间:2017-02-03 02:25:45

标签: python list dictionary random

我试图从列表字典中随机选择特定数量的序列,然后将这些序列附加到新列表,但我一直收到一个空列表。我的代码:

final_List = []
num = [["ENST", "10", "5"], ["ENGT", "8", "2"], ["ENHT", "5", "1"]]
a = {"ENST" : ['acac', 'tgtgtgt', 'hahah'], "ENHT": ['aaaa', 'tttt', 'gig', 
'cccc'], 'ENGT' : ['ddd', 'eeee', 'ffff', 'hhhh', 'pppp']}

for line in num:
    for k, v in a.items():
        if line[0] == k:
            for i in int(line[1] -1):
                final_List.append([k, random.choice(0, len(v))])

我将line [0]与k进行比较,如果它们相同,我想从v中提取随机序列。我想要的序列数是第[1]行的数字。 final_List看起来像:

final_List = [["ENST", "acac"], ["ENST", tgtgtgt"]...10 lists with header "ENST"
              ["ENGT", "ddd"], .....8 lists with header "ENGT"
              ["ENHT","aaaa"], ..... 5 lists with header "ENHT"

3 个答案:

答案 0 :(得分:1)

您可以使用嵌套列表理解:

>>> import pprint
>>> import random
>>> num = [["ENST", "10", "5"], ["ENGT", "8", "2"], ["ENHT", "5", "1"]]
>>> a = {"ENST" : ['acac', 'tgtgtgt', 'hahah'], "ENHT": ['aaaa', 'tttt', 'gig', 
... 'cccc'], 'ENGT' : ['ddd', 'eeee', 'ffff', 'hhhh', 'pppp']}
>>> res = [[[k, random.choice(a[k])] for _ in range(int(count))] for k, count, _ in num]
>>> pprint.pprint(res)
[[['ENST', 'acac'],
  ['ENST', 'tgtgtgt'],
  ['ENST', 'hahah'],
  ['ENST', 'hahah'],
  ['ENST', 'tgtgtgt'],
  ['ENST', 'tgtgtgt'],
  ['ENST', 'hahah'],
  ['ENST', 'acac'],
  ['ENST', 'acac'],
  ['ENST', 'tgtgtgt']],
 [['ENGT', 'pppp'],
  ['ENGT', 'ffff'],
  ['ENGT', 'eeee'],
  ['ENGT', 'hhhh'],
  ['ENGT', 'pppp'],
  ['ENGT', 'eeee'],
  ['ENGT', 'pppp'],
  ['ENGT', 'pppp']],
 [['ENHT', 'cccc'],
  ['ENHT', 'aaaa'],
  ['ENHT', 'gig'],
  ['ENHT', 'tttt'],
  ['ENHT', 'cccc']]]

在上面for k, count, _ in num将迭代num中的元素并将它们解压缩到各自的变量中。请注意,我们只需要名称和计数,因此一次性变量名为_

>>> [(k, count) for k, count, _ in num]
[('ENST', '10'), ('ENGT', '8'), ('ENHT', '5')]

对于num中的每个元素,通过counta的{​​{1}}中相应列表中的>>> k = 'ENST' >>> count = '10' >>> [[k, random.choice(a[k])] for _ in range(int(count))] [['ENST', 'tgtgtgt'], ['ENST', 'hahah'], ['ENST', 'acac'], ['ENST', 'hahah'], ['ENST', 'tgtgtgt'], ['ENST', 'hahah'], ['ENST', 'hahah'], ['ENST', 'hahah'], ['ENST', 'acac'], ['ENST', 'acac']] 个元素来构建列表:

import random
def flip():
    flipValue = random.randint(1,2)
    if flipValue == 1:
        side = "Heads"
    else:
        side = "Tails"
    return side

def nStreak():
    numFlips = int(input("Number of flips:"))
    lengthStreak = int(input("Length of streak:"))
    numRuns = 0
    heads = 0
    tails = 0
    numStreakHeads = 0
    numStreakTails = 0
    while numRuns != numFlips:
        side = flip()
        numRuns += 1
        if side == "Heads":
            heads += 1
            tails = 0
            if heads == lengthStreak:
                numStreakHeads += 1
                heads = 0
        if side == "Tails":
            tails += 1
            heads = 0
            if tails == lengthStreak:
                numStreakTails += 1
                tails = 0
    print("Number of heads streaks:", numStreakHeads)
    print("Number of tails streaks:", numStreakTails) 

答案 1 :(得分:0)

问题在于您进行随机选择。您错误地使用了random.choice。此外,我们希望确保您正确地在行[1]上进行迭代。这些行:

for i in int(line[1] -1):
    final_List.append([k, random.choice(0, len(v))])

应该是

for i in range(int(line[1])):
    final_List.append([k, random.choice(v)])

答案 2 :(得分:0)

类似于列表理解的想法,但我会使用一个函数来使它更清晰

def create_sequence(hdr, count):
     return [[hdr, random.choice(a[hdr])] for _ in range(count)]

final_list = [create_sequence(hdr, int(count)) for hdr,count,_ in num]