![](/img/trans.png)
[英]Python: Tie breaker when sorting a list of tuples (max for first element, and 1st occurrence of the second)
[英]Python sorting tuples by first and second element
我正在使用从STDIN接收输入的python脚本。 我无法访问输入中数据的排序方式。
输入中的每一行具有以下形式:
(Int,Int) \t Int
现在,当数据进入时,它是按元组排序的,但是不正确。 所以看起来像这样:
(0,1) 5
(0,10) 2
(0,2) 3
(1,8) 7
(1,82) 5
(1,9) 4
现在这是错误的,因为我希望它们按照元组中的第一个元素然后第二个元素进行排序-因此它应该像这样:
(0,1) 5
(0,2) 3
(0,10) 2
(1,8) 7
(1,9) 4
(1,82) 5
我的问题是线路是一一穿过的。 因此,在它们进入后,我必须对其进行排序。
我试图分配一个数组,当一个新的元组出现时,我试图将其插入适当的位置,但这似乎与Python的数组概念相矛盾。
我将如何解决这个问题?
也许,这将更好地适合您:
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
:
(0,1) 5
(0,10) 2
(0,2) 3
(1,8) 7
(1,82) 5
(1,9) 4
和输出,正如您所期望的:
[(('0', '1'), 5), (('0', '2'), 3), (('0', '10'), 2), (('1', '8'), 7), (('1', '9'), 4), (('1', '82'), 5)]
注–避免使用eval
。 像GamesBraniac一样进行类型转换。 你可以做这样的事情
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
提供输出
[[(0, 1), 5], [(0, 2), 3], [(0, 10), 2], [(1, 8), 7], [(1, 9), 4], [(1, 82), 5]]
对于漂亮的输出,你可以做
>>>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]
将为您提供标签左侧的项目。 ast.literal_eval()
会将其转换为2整数元组。 使用itertools.groupby()
可以删除第一个元素的排序,因为它是按排序的。 排序组中的第二个元素,以便按第二个元素排序。 将新排序的组追加到现有数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.