簡體   English   中英

Python按第一和第二個元素對元組進行排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM