简体   繁体   English

列表python的排列

[英]Permutations of a list python

I need to define a function apply(L, P) where L is a list and P is a permutation, and it should return the list L o P. Assume len(L) = len(P) 我需要定义一个函数apply(L,P),其中L是一个列表,P是一个排列,它应该返回列表L oP。假设len(L) = len(P)

What I've got so far is 到目前为止,我得到的是

import itertools 
def apply(L, P):
    for perm in L:
        return perm

An example of input is apply(['ah', 'boo', 'cc', 'du', 'eh'], [1, 4, 3, 2, 0]) But the only output from that is 'ah' 输入的示例是apply(['ah', 'boo', 'cc', 'du', 'eh'], [1, 4, 3, 2, 0])但是唯一的输出是'ah'

Any help would be great. 任何帮助都会很棒。

This sounds like a task most easily achieved with a list comprehension: 这听起来像是通过列表理解最容易完成的任务:

>>> def apply(L, P):
...   return [ L[i] for i in P ]
... 
>>> apply(['ah', 'boo', 'cc', 'du', 'eh'], [1, 4, 3, 2, 0])
['boo', 'eh', 'du', 'cc', 'ah']

Here's my version: 这是我的版本:

def apply(L, P):
    newL = [None]*len(L)
    for i,index in enumerate(P):
        newL[i] = L[index]
    return newL

This can easily be accomplished in one line in python, but I wanted to illustrate what's happening here. 这很容易在python的一行中完成,但是我想说明一下这里发生的事情。

The entire list is created before returning. 整个列表在返回之前创建。 return means that the function should exit and return the specified value. return表示该函数应退出并返回指定的值。 In your case that is 'ah' since it's the first element in the list you're looping through. 在您的情况下为'ah'因为它是您要遍历的列表中的第一个元素。

If you want to learn python, check out svk's very pythonic list comprehension. 如果您想学习python,请查看svk的pythonic列表理解。

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

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