簡體   English   中英

用隨機項目填充列表列表

[英]Populating a list of lists with random items

我有一個具有一定范圍的列表列表:

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

有任何想法嗎? 先感謝您!

您可以為此使用列表推導:

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']]

您沒有將值存儲回列表中。 嘗試:

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

您應該展平列表列表,然后隨機播放,然后重新構建。 例:

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]]

這將在所有列表中隨機分配,而不僅僅是在單個子列表中,並且保證不會出現重復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM