简体   繁体   English

是否有 function 使用 python 在唯一索引中创建唯一元素列表?

[英]Is there a function to create a list of unique elements in unique index using python?

Is there a way to create a new set of lists of elements, with each element of the original list in a unique index in the following lists?有没有办法创建一组新的元素列表,原始列表的每个元素都在以下列表中的唯一索引中?

orginal_list=['r', 'g', 'b', 'y']

output: ['y', 'g', 'r', 'b'],['g', 'y', 'b', 'r'],['r', 'b', 'y', 'g'],['b', 'r', 'g', 'y']
or
output: ['y', 'r', 'b', 'g'],['g', 'y', 'r', 'b'],['r', 'b', 'g', 'y'],['b', 'g', 'y', 'r']
or 
...

I have tried to use iterators.permutations , but this does not fit with the unique index requirement.我曾尝试使用iterators.permutations ,但这不符合唯一索引要求。

Easiest would be to rotate the list.最简单的方法是轮换列表。 Here is a simple generator function producing all such rotations:这是一个简单的生成器 function 产生所有这样的旋转:

def rots(lst):
    for i in range(len(lst)):
        yield lst[i:] + lst[:i]

>>> list(rots(['r', 'g', 'b', 'y']))
[['r', 'g', 'b', 'y'], 
 ['g', 'b', 'y', 'r'], 
 ['b', 'y', 'r', 'g'], 
 ['y', 'r', 'g', 'b']]

The rotating guarantees that each element actually occurs in each index exactly once.旋转保证每个元素在每个索引中实际出现一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM