2017-07-06 43 views
0

我有一個列表的列表與一定範圍內:填充列表的列表隨機物品

l = [["this", "is", "a"], ["list", "of"], ["lists", "that", "i", "want"], ["to", "copy"]] 

而且單詞的列表:

words = ["lorem", "ipsum", "dolor", "sit", "amet", "id", "sint", "risus", "per", "ut", "enim", "velit", "nunc", "ultricies"] 

我需要創建的翻版列表的列表,但從另一個列表中挑選的隨機詞彙。

這是首先想到的,但沒有骰子。

for random.choice in words: 
    for x in list: 
    for y in x: 
     y = random.choice 

任何想法?先謝謝你!

+5

請顯示您的兩個輸入列表,以及一些示例輸出。現在有點難以理解你想要做什麼。 –

+0

這不就是洗牌嗎? –

+0

你知道'=='是一個平等檢查,而不是一項任務,對嗎? – C8H10N4O2

回答

4

您可以使用列表理解爲這樣的:

import random 
my_list = [[1, 2, 3], [5, 6]] 
words = ['hello', 'Python'] 

new_list = [[random.choice(words) for y in x] for x in my_list] 
print(new_list) 

輸出:

[['Python', 'Python', 'hello'], ['Python', 'hello']] 

這相當於:

new_list = [] 
for x in my_list: 
    subl = [] 
    for y in x: 
     subl.append(random.choice(words)) 
    new_list.append(subl) 

與您的數據。例如:

my_list = [['this', 'is', 'a'], ['list', 'of'], 
      ['lists', 'that', 'i', 'want'], ['to', 'copy']] 

words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet', 'id', 'sint', 'risus', 
     'per', 'ut', 'enim', 'velit', 'nunc', 'ultricies'] 
new_list = [[random.choice(words) for y in x] for x in my_list] 
print(new_list) 

輸出:

[['enim', 'risus', 'sint'], ['dolor', 'lorem'], ['sint', 'nunc', 'ut', 'lorem'], ['ipsum', 'amet']] 
+0

感謝邁克,工作就像一個魅力。我有正確的方向,但與執行不力:) – DJM

1

您不會將值存儲回您的列表中。嘗試:

for i in range(0, len(list)): 
    subl = list[i] 
    for n in range(0, len(subl)): 
     list[i][n] = random.choice(words) 
+0

你是對的,謝謝! – DJM

1

您應彙整清單列表,然後洗牌,然後重建。例如:

import random 

def super_shuffle(lol): 
    sublist_lengths = [len(sublist) for sublist in lol] 
    flat = [item for sublist in lol for item in sublist] 
    random.shuffle(flat) 
    pos = 0 
    shuffled_lol = [] 
    for length in sublist_lengths: 
    shuffled_lol.append(flat[pos:pos+length]) 
    pos += length 
    return shuffled_lol 

print super_shuffle([[1,2,3,4],[5,6,7],[8,9]]) 

打印:

[[7, 8, 5, 6], [9, 1, 3], [2, 4]] 

這會隨機在所有名單,不只是在一個單一的子表,並保證沒有的DUP。

+0

肯定也會嘗試這一個,謝謝! – DJM