简体   繁体   English

Python按第一和第二个元素对元组进行排序

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

相关问题 Python:排序元组列表时的决胜局(第一个元素的最大值,第二个元素的第一次出现) - Python: Tie breaker when sorting a list of tuples (max for first element, and 1st occurrence of the second) 如何获取具有匹配的第二个元素的元组的第一个元素(python) - how to get first element of tuples with matching second element (python) Python3:按元组第一个元素中包含的数据戳对元组列表进行排序 - Python3: Sorting a list of tuples by datastamp contained in first element of tuple Python:基于第一个元素对数组中的元组进行排序 - Python: Sorting Tuples in array based off first element 按每个元组的第一个元素对元组列表进行排序-Python 2.7 - Sorting list of tuples by first element of each tuple - Python 2.7 Python元组列表中第二个和第三个元素的和,按第一个分组 - Python sum of second and third element of tuple in list of tuples grouped by first python 元组在第一个元素上随机播放保持第二顺序 - python tuples shuffle on first element keep second ordering 在Python中按元素值对元组进行排序 - Sorting tuples by element value in Python 根据字典中列表中元组的第二个元素排序 - Sorting according to Second Element of Tuples in Lists in a Dictionary Python按第一个元素的最大值,然后第二个元素的最小值排序 - Python sorting by the max of the first element, then the min of the second element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM