[英]Python sorting tuples by first and second element
I am using a python script that takes input from STDIN. 我正在使用从STDIN接收输入的python脚本。 I have no access as to how the data is sorted in the input.
我无法访问输入中数据的排序方式。
Each line in the input has the following form: 输入中的每一行具有以下形式:
(Int,Int) \t Int
Now when the data comes in it's sorted by the tuples, but not properly. 现在,当数据进入时,它是按元组排序的,但是不正确。 So it looks something like this:
所以看起来像这样:
(0,1) 5
(0,10) 2
(0,2) 3
(1,8) 7
(1,82) 5
(1,9) 4
Now this is wrong since I'd like them sorted by first and then by the second element in the tuple - so it should look like this: 现在这是错误的,因为我希望它们按照元组中的第一个元素然后第二个元素进行排序-因此它应该像这样:
(0,1) 5
(0,2) 3
(0,10) 2
(1,8) 7
(1,9) 4
(1,82) 5
My problem is that the lines are coming through one by one. 我的问题是线路是一一穿过的。 So I have to sort them after they come in.
因此,在它们进入后,我必须对其进行排序。
I tried to allocate an array and when a new tuple comes in - I tried to insert it in its proper place, but that seems to be contradicting Python's notion of arrays. 我试图分配一个数组,当一个新的元组出现时,我试图将其插入适当的位置,但这似乎与Python的数组概念相矛盾。
How would I approach this problem? 我将如何解决这个问题?
Perhaps, this will better suite you: 也许,这将更好地适合您:
with open('stuff.txt', 'r') as f:
store = []
for line in f:
tup, num = line.split()
tup = tuple(map(int, tup[1:-1].split(',')))
num = int(num)
store.append((tup, num))
print sorted(store)
Stuff.txt
: Stuff.txt
:
(0,1) 5
(0,10) 2
(0,2) 3
(1,8) 7
(1,82) 5
(1,9) 4
And the output, as you would expect: 和输出,正如您所期望的:
[(('0', '1'), 5), (('0', '2'), 3), (('0', '10'), 2), (('1', '8'), 7), (('1', '9'), 4), (('1', '82'), 5)]
Note - Avoid using eval
. 注–避免使用
eval
。 Do the type casting like GamesBraniac did. 像GamesBraniac一样进行类型转换。 You can do something like this
你可以做这样的事情
with open("input_file.txt") as input_file:
sorted_array = []
for line in input_file:
tup, val = map(eval, line.split())
# Verify the input data
try:
assert type(tup) == tuple
assert type(val) == int
sorted_array.append([tup, val])
except:
print "Invalid input"
sorted_array.sort()
print sorted_array
Gives output 提供输出
[[(0, 1), 5], [(0, 2), 3], [(0, 10), 2], [(1, 8), 7], [(1, 9), 4], [(1, 82), 5]]
For pretty output, you could do 对于漂亮的输出,你可以做
>>>for tup, val in sorted_array:
... print "{0}\t{1}".format(tup, val)
>>>
(0, 1) 5
(0, 2) 3
(0, 10) 2
(1, 8) 7
(1, 9) 4
(1, 82) 5
>>>
line.split('\\t')[0]
will give you the items to the left of the tab. line.split('\\t')[0]
将为您提供标签左侧的项目。 ast.literal_eval()
will turn that into 2-integer tuples. ast.literal_eval()
会将其转换为2整数元组。 Use itertools.groupby()
to remove sorting by the first element, since it comes in sorted. 使用
itertools.groupby()
可以删除第一个元素的排序,因为它是按排序的。 Sort the second element of the group in order to sort by the second element. 排序组中的第二个元素,以便按第二个元素排序。 Append the new sorted groups to the existing data.
将新排序的组追加到现有数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.