将值插入列表中所有可能的位置 [英] Inserting a value into all possible locations in a list
本文介绍了将值插入列表中所有可能的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打印给定列表的所有可能结果,并且我想知道如何将值放入列表中的各个位置.例如,如果我的列表是[A, B]
,我想将X
插入到列表的所有可能的索引中,这样它将返回此[X, A, B]
,[A, X, B]
,[A, B, X]
.
I am trying to do print all the possible outcomes of a given list and I was wondering how to put a value into various locations in the list. For example, if my list was [A, B]
, I want to insert X
into all possible index of the list such that it would return this [X, A, B]
, [A, X, B]
, [A, B, X]
.
我正在考虑使用range(len())
和for循环,但不确定如何启动.
I was thinking about using range(len())
and a for loop but not sure how to start.
推荐答案
您可以通过以下列表理解来做到这一点:
You could do this with the following list comprehension:
[mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]
以您的示例为例:
>>> mylist=['A','B']
>>> newelement='X'
>>> [mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)]
[['X', 'A', 'B'], ['B', 'X', 'A'], ['A', 'B', 'X']]
这篇关于将值插入列表中所有可能的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文