如何在不使用可选参数`key`的情况下对嵌套列表进行排序

时间:2017-12-04 04:11:00

标签: python list sorting for-loop tuples

我有点像家庭作业问题。 假设我有一个列表:

sort

我必须编写一个函数,使列表按第二个元素排序,即整数值。此外,如果两个人有相同的整数,那么我必须按字母顺序排序。此外,我被允许使用key,但我不能使用可选参数[('Mitchell Piker', 3), ('Luke Skywalker', 2), ('Paul George', 1), ('Phil Dam', 1)]。所以我应该有这样的事情:

>>> def sort(lst: List[Tuple[str, int]]): """Return the list of tuples from largest integer score to lowest integer score. If two people have the same score, then sort them by alphabetical order. """ lst2 = [] lst2.append(lst[0]) for i in range(len(lst)): for j in range(len(lst2)): if lst[i][-1] > lst2[j][-1] and lst[i][-1] not in lst2: lst2.insert(0, lst2[i]) if lst[i][-1] < lst2[j][-1] and lst[i][-1] not in lst2: lst2.append(lst2[i][-1]) return lst2

  File "./jobs.zip/jobs/util.py", line 51, in wrapped
    cython_function_ = getattr(__import__(module), method)
  File "/usr/local/lib64/python2.7/site-packages/pyximport/pyximport.py", line 458, in load_module
    language_level=self.language_level)
  File "/usr/local/lib64/python2.7/site-packages/pyximport/pyximport.py", line 233, in load_module
    exec("raise exc, None, tb", {'exc': exc, 'tb': tb})
  File "/usr/local/lib64/python2.7/site-packages/pyximport/pyximport.py", line 216, in load_module
    mod = imp.load_dynamic(name, so_path)
ImportError: Building module cython_util failed: ['ImportError: /home/.pyxbld/lib.linux-x86_64-2.7/cython_util.so: file too short\n']

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.<init>(PythonRDD.scala:234)
    at org.apache.spark.api.python.PythonRunner.compute(PythonRDD.scala:152)
    at org.apache.spark.api.python.PythonRDD.compute(PythonRDD.scala:63)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:108)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

然而我收到错误。有人可以帮忙吗?非常感谢你

4 个答案:

答案 0 :(得分:1)

如果可以假设数字总是整数,你可以使用它们来索引值,就像这样(它也可以通过排序而不是排序来实现)

groups = defaultdict(list)
max_id = -1
for name, idx in lst:
    groups[idx].append(name)
    if max_id < idx:
        max_id = idx
result = [(name, idx) for idx in range(max_id, -1, -1) for name in sorted(groups.get(idx, []))]
# [('Mitchell Piker', 3), ('Luke Skywalker', 2), ('Paul George', 1), ('Phil Dam', 1)]

编辑:

from collections import defaultdict
groups = defaultdict(list)
for name, idx in lst:
    groups[idx].append(name)
[(name, idx) for idx in sorted(groups.keys())[::-1] for name in sorted(groups[idx])]

注意:如果您反对使用groups.keys(),则可以始终使用[x for x in groups]代替...

答案 1 :(得分:0)

假设函数的签名只是在问题中搞砸了(否则代码会引发NameError

问题在于这一行:

for j in range(len(lst2))

lst2的长度为零 - 循环永远不会执行...

答案 2 :(得分:0)

怎么样?

lst = [('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3), ('Phil Dam', 1)]

[(n,-i) for (i,n) in sorted([(-i,n) for (n,i) in lst])]


[('Mitchell Piker', 3),
 ('Luke Skywalker', 2),
 ('Paul George', 1),
 ('Phil Dam', 1)]

说明:sorted做你想要的,除了:

  • 它将根据第一个元素(名称)排序

  • 然后根据第二个元素(数字)排序,但也按升序排序

所以要解决这个问题:用元素交换将其夹在中间以及否定数字。

答案 3 :(得分:0)

您可以尝试这样的事情:

仅针对test_case,我已经编辑了名称以获得更高的准确性:

your_data=[('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3), ('Ahil Dam', 1)]

new={}
for item in your_data:
    if item[1] not in new:
        new[item[1]]=[item[0]]
    else:
        new[item[1]].append(item[0])


    for key,value in new.items():
        if len(value)>1:

            new[key]=sorted(value)



final_list=[]
for key,value in new.items():
    if len(value) > 1:
        for sub_item in value:
            final_list.append((sub_item,key))
    else:
        final_list.append(("".join(value),key))


print(final_list)

输出:

[('Ahil Dam', 1), ('Paul George', 1), ('Luke Skywalker', 2), ('Mitchell Piker', 3)]

或者如果您想要这样的结果,那么只需反转最终结果:

print(final_list[::-1])