问题:如何重新排序列表?[关闭]

如果我有列表,[a,b,c,d,e]如何以任意方式重新排序商品[d,c,a,b,e]

编辑:我不想洗牌。我想以预定义的方式重新排序。(例如,我知道旧列表中的第3个元素应成为新列表中的第一个元素)

If I have a list [a,b,c,d,e] how can I reorder the items in an arbitrary manner like [d,c,a,b,e]?

Edit: I don’t want to shuffle them. I want to re-order them in a predefined manner. (for example, I know that the 3rd element in the old list should become the first element in the new list)


回答 0

你可以这样

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']

You can do it like this

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']

回答 1

>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]
>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]

回答 2

>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]
>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]

回答 3

最终顺序是否由索引列表定义?

>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]

>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']

编辑:嗯。AJ速度更快… 如何在python中重新排序列表?

Is the final order defined by a list of indices ?

>>> items = [1, None, "chicken", int]
>>> order = [3, 0, 1, 2]

>>> ordered_list = [items[i] for i in order]
>>> ordered_list
[<type 'int'>, 1, None, 'chicken']

edit: meh. AJ was faster… How can I reorder a list in python?


回答 4

>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']
>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']

回答 5

您可以提供自己的排序功能list.sort()

sort()方法采用可选参数来控制比较。

  • cmp指定了两个参数(列表项)的自定义比较函数,该函数应返回负数,零数或正数,具体取决于第一个参数是否小于,等于或大于第二个参数:cmp=lambda x,y: cmp(x.lower(), y.lower())。默认值为None

  • key指定一个参数的功能,该参数用于从每个列表元素中提取比较键:key=str.lower。默认值为None

  • reverse是一个布尔值。如果设置为True,则对列表元素进行排序,就好像每个比较都被反转一样。

通常,键和反向转换过程比指定等效的cmp函数要快得多。这是因为对于每个列表元素,cmp被多次调用,而按键和反向触摸每个元素仅一次。

You can provide your own sort function to list.sort():

The sort() method takes optional arguments for controlling the comparisons.

  • cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

  • key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

  • reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once.


回答 6

如果您使用numpy,则有一种简洁的方法:

items = np.array(["a","b","c","d"])
indices = np.arange(items.shape[0])
np.random.shuffle(indices)
print(indices)
print(items[indices])

此代码返回:

[1 3 2 0]
['b' 'd' 'c' 'a']

If you use numpy there’s a neat way to do it:

items = np.array(["a","b","c","d"])
indices = np.arange(items.shape[0])
np.random.shuffle(indices)
print(indices)
print(items[indices])

This code returns:

[1 3 2 0]
['b' 'd' 'c' 'a']

回答 7

如果您不太在乎效率,则可以依靠numpy的数组索引使其优雅:

a = ['123', 'abc', 456]
order = [2, 0, 1]
a2 = list( np.array(a, dtype=object)[order] )

If you do not care so much about efficiency, you could rely on numpy’s array indexing to make it elegant:

a = ['123', 'abc', 456]
order = [2, 0, 1]
a2 = list( np.array(a, dtype=object)[order] )

回答 8

据我对您的问题的了解,您似乎想应用在上指定的排列list。这可以通过指定另一个list(让我们称之为p)来保存list应出现在置换中的原始元素的索引来完成list。然后p,您可以list通过简单地将每个位置的元素替换为索引中位于该位置的元素来制作新的元素p

def apply_permutation(lst, p):
    return [lst[x] for x in p]

arr=list("abcde")
new_order=[3,2,0,1,4]

print apply_permutation(arr,new_order)

打印['d', 'c', 'a', 'b', 'e']

实际上list,这会创建一个新的,但可以对其进行微不足道的修改以置换原始的“就地”。

From what I understand of your question, it appears that you want to apply a permutation that you specify on a list. This is done by specifying another list (lets call it p) that holds the indices of the elements of the original list that should appear in the permuted list. You then use p to make a new list by simply substituting the element at each position by that whose index is in that position in p.

def apply_permutation(lst, p):
    return [lst[x] for x in p]

arr=list("abcde")
new_order=[3,2,0,1,4]

print apply_permutation(arr,new_order)

This prints ['d', 'c', 'a', 'b', 'e'].

This actually creates a new list, but it can be trivially modified to permute the original “in place”.


回答 9

可以考虑的另一件事是“黑暗”指出的另一种解释

Python 2.7中的代码

主要是:

  1. 按值重新排序-已经由上述AJ解决
  2. 按索引重新排序

    mylist = ['a', 'b', 'c', 'd', 'e']
    myorder = [3, 2, 0, 1, 4]
    
    mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
    print [item[0] for item in mylist]

这将打印[‘c’,’d’,’b’,’a’,’e’]

One more thing which can be considered is the other interpretation as pointed out by darkless

Code in Python 2.7

Mainly:

  1. Reorder by value – Already solved by AJ above
  2. Reorder by index

    mylist = ['a', 'b', 'c', 'd', 'e']
    myorder = [3, 2, 0, 1, 4]
    
    mylist = sorted(zip(mylist, myorder), key=lambda x: x[1])
    print [item[0] for item in mylist]
    

This will print [‘c’, ‘d’, ‘b’, ‘a’, ‘e’]


回答 10

newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])
newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])

回答 11

这是我偶然发现此问题时使用的方法。

def order(list_item, i): # reorder at index i
    order_at = list_item.index(i)
    ordered_list = list_item[order_at:] + list_item[:order_at]
    return ordered_list

EX:小写字母

order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'

它只是将列表移动到指定索引

This is what I used when I stumbled upon this problem.

def order(list_item, i): # reorder at index i
    order_at = list_item.index(i)
    ordered_list = list_item[order_at:] + list_item[:order_at]
    return ordered_list

EX: for the the lowercase letters

order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'

It simply just shifts the list to a specified index


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。