您可以使用 Python 中的 random.shuffle() 函数来随机排列每个子列表中的元素。但是,这只会打乱每个子列表中的元素,而不是跨子列表。
要在所有子列表中一致地随机排列元素,您可以结合使用 random.shuffle() 函数和原始元素到新元素的映射。这是您可以做到的一种方法:
import random
# Initial list of lists
list_of_lists = [['A','C'], ['A','D'], ['B','A'], ['F','B']]
# Create a list of all unique elements in the initial list of lists
elements = list(set([elem for sublist in list_of_lists for elem in sublist]))
# Shuffle the elements
random.shuffle(elements)
# Create a mapping of original elements to new elements
mapping = {elem: new_elem for elem, new_elem in zip(elements, elements[1:] + [elements[0]])}
# Replace the elements in the initial list of lists with their new values using the mapping
shuffled_list_of_lists = [[mapping[elem] for elem in sublist] for sublist in list_of_lists]
print(shuffled_list_of_lists)
这将例如输出:
[['B','D'], ['B','A'], ['E','B'], ['C','E']]
这段代码在原始元素和新元素之间创建了一个映射,然后使用嵌套列表理解根据映射用新值替换列表初始列表中的元素。