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]
?
如果我有一个列表[a,b,c,d,e]我怎样才能以[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)
编辑:我不想洗牌他们。我想以预定义的方式重新排序它们。 (例如,我知道旧列表中的第3个元素应该成为新列表中的第一个元素)
11 个解决方案
#1
156
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
#2
8
>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]
#3
4
>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]
#4
4
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?
编辑:嗯。 AJ更快......如何在python中重新排序列表?
#5
2
You can provide your own sort function to list.sort()
:
您可以为list.sort()提供自己的排序功能:
The sort() method takes optional arguments for controlling the comparisons.
sort()方法采用可选参数来控制比较。
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 isNone
.cmp指定两个参数(列表项)的自定义比较函数,它应返回负数,零或正数,具体取决于第一个参数是否被认为小于,等于或大于第二个参数:cmp = lambda x,y :cmp(x.lower(),y.lower())。默认值为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 isNone
.key指定一个参数的函数,该函数用于从每个列表元素中提取比较键:key = str.lower。默认值为None。
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
reverse是一个布尔值。如果设置为True,则列表元素将按照每个比较相反的方式进行排序。
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.
通常,键和反向转换过程比指定等效的cmp函数快得多。这是因为对于每个列表元素多次调用cmp,而键和反向触摸每个元素仅一次。
#6
1
>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']
#7
1
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
.
根据我对您的问题的理解,您似乎想要应用您在列表中指定的排列。这是通过指定另一个列表(让我们称之为p)来完成的,该列表包含应该出现在置换列表中的原始列表元素的索引。然后使用p创建一个新列表,只需用每个位置的元素替换其索引位于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']
.
这打印['d','c','a','b','e']。
This actually creates a new list
, but it can be trivially modified to permute the original "in place".
这实际上创建了一个新的列表,但它可以通过简单的修改来置换原始的“就地”。
#8
1
If you use numpy there's a neat way to do it:
如果你使用numpy有一个简洁的方法来做到这一点:
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']
#9
0
newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])
#10
0
One more thing which can be considered is the other interpretation as pointed out by darkless
可以考虑的另一件事是无暗指出的另一种解释
Code in Python 2.7
Python 2.7中的代码
Mainly:
主要是:
- Reorder by value - Already solved by AJ above
- 按值重新排序 - 已由上面的AJ解决
-
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']
这将打印['c','d','b','a','e']
#11
0
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
EX:用于小写字母
order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'
It simply just shifts the list to a specified index
它只是将列表移动到指定的索引
#1
156
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
#2
8
>>> import random
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)
>>> x
[5, 2, 4, 3, 1]
#3
4
>>> a = [1, 2, 3]
>>> a[0], a[2] = a[2], a[0]
>>> a
[3, 2, 1]
#4
4
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?
编辑:嗯。 AJ更快......如何在python中重新排序列表?
#5
2
You can provide your own sort function to list.sort()
:
您可以为list.sort()提供自己的排序功能:
The sort() method takes optional arguments for controlling the comparisons.
sort()方法采用可选参数来控制比较。
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 isNone
.cmp指定两个参数(列表项)的自定义比较函数,它应返回负数,零或正数,具体取决于第一个参数是否被认为小于,等于或大于第二个参数:cmp = lambda x,y :cmp(x.lower(),y.lower())。默认值为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 isNone
.key指定一个参数的函数,该函数用于从每个列表元素中提取比较键:key = str.lower。默认值为None。
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
reverse是一个布尔值。如果设置为True,则列表元素将按照每个比较相反的方式进行排序。
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.
通常,键和反向转换过程比指定等效的cmp函数快得多。这是因为对于每个列表元素多次调用cmp,而键和反向触摸每个元素仅一次。
#6
1
>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']
#7
1
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
.
根据我对您的问题的理解,您似乎想要应用您在列表中指定的排列。这是通过指定另一个列表(让我们称之为p)来完成的,该列表包含应该出现在置换列表中的原始列表元素的索引。然后使用p创建一个新列表,只需用每个位置的元素替换其索引位于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']
.
这打印['d','c','a','b','e']。
This actually creates a new list
, but it can be trivially modified to permute the original "in place".
这实际上创建了一个新的列表,但它可以通过简单的修改来置换原始的“就地”。
#8
1
If you use numpy there's a neat way to do it:
如果你使用numpy有一个简洁的方法来做到这一点:
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']
#9
0
newList = [oldList[3]]
newList.extend(oldList[:3])
newList.extend(oldList[4:])
#10
0
One more thing which can be considered is the other interpretation as pointed out by darkless
可以考虑的另一件事是无暗指出的另一种解释
Code in Python 2.7
Python 2.7中的代码
Mainly:
主要是:
- Reorder by value - Already solved by AJ above
- 按值重新排序 - 已由上面的AJ解决
-
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']
这将打印['c','d','b','a','e']
#11
0
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
EX:用于小写字母
order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'
It simply just shifts the list to a specified index
它只是将列表移动到指定的索引