我有一个具有特定范围的列表列表:
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
有什么想法吗?提前谢谢!
答案 0 :(得分: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']]
答案 1 :(得分:1)
您未将值存储回列表中。尝试:
import multiprocessing as mp
query_points = query_points.tolist()
parallel = mp.Pool()
fv = parallel.map(par_gmm, query_points)
parallel.close()
parallel.join()
答案 2 :(得分: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]]
这会在所有列表中随机化,而不仅仅在单个子列表中,并保证不会重复。