GCi*_*ien 7 python arrays sorting
如果我有两个形式的数组:
x = [0, 7, 2, 4, 6, 9, 5]
y = [1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)
也就是说,我有个数据点[0,1],[3,2],[x_n,y_n]等我将如何组织y一个corresonding上升x的价值?换句话说,我最终得到的升值x:
x = [0, 2, 4, 5, 6, 7, 9]
Run Code Online (Sandbox Code Playgroud)
与其对应的y值匹配:
y = [1, 3, 4, 7, 5, 2, 6]
Run Code Online (Sandbox Code Playgroud)
我猜我需要将两个数组拼接在一起,然后按照排序x,但我不太确定这个的确切语法.任何帮助将不胜感激.
我会用zip一个lambda:
In [55]: x = [0, 7, 2, 4, 6, 9, 5]
In [56]: y = [1, 2, 3, 4, 5, 6, 7]
In [57]: L = sorted(zip(x,y), key=operator.itemgetter(0))
In [58]: new_x, new_y = zip(*L)
In [59]: new_x
Out[59]: (0, 2, 4, 5, 6, 7, 9)
In [60]: new_y
Out[60]: (1, 3, 4, 7, 5, 2, 6)
Run Code Online (Sandbox Code Playgroud)
别忘了导入 operator
你可以将sorted它们作为元组在你zip之后
>>> sorted((i,j) for i,j in zip(x,y))
[(0, 1), (2, 3), (4, 4), (5, 7), (6, 5), (7, 2), (9, 6)]
Run Code Online (Sandbox Code Playgroud)
要迭代这些对,您可以执行类似的操作
sorted_pairs = sorted((i,j) for i,j in zip(x,y))
for i,j in sorted_pairs:
# do something with each i and j value, which are x and y respectively
Run Code Online (Sandbox Code Playgroud)
或者你可以直接索引
sorted_pairs[0][0] # x of the first tuple
sorted_pairs[0][1] # y of the first tuple
sorted_pairs[3][0] # x of the fourth tuple... etc
Run Code Online (Sandbox Code Playgroud)