我正在使用一个从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的数组概念相矛盾。
我该如何解决这个问题?
答案 0 :(得分:4)
也许,这会更好地适应你:
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)]
答案 1 :(得分:2)
注意 - 避免使用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
>>>
答案 2 :(得分:1)
line.split('\t')[0]
会为您提供标签左侧的项目。 ast.literal_eval()
会将其转换为2整数元组。使用itertools.groupby()
删除第一个元素的排序,因为它是排序的。对组的第二个元素进行排序,以便按第二个元素排序。将新排序的组附加到现有数据。