Python:关于排序

时间:2018-03-14 03:29:08

标签: python sorting

我注意到两条线的结果不同。一个是排序列表,而另一个是排序字典。无法弄清楚为什么添加.item会产生这种差异:

aa={'a':1,'d':2,'c':3,'b':4}
bb=sorted(aa,key=lambda x:x[0])
print(bb)

#['a', 'b', 'c', 'd']

aa={'a':1,'d':2,'c':3,'b':4}
bb=sorted(aa.items(),key=lambda x:x[0])
print(bb)

# [('a', 1), ('b', 4), ('c', 3), ('d', 2)]

3 个答案:

答案 0 :(得分:2)

第一个版本隐式地对字典中的进行排序,相当于排序aa.keys()。第二个版本对进行排序,即:(key, value)形式的元组列表。

答案 1 :(得分:0)

当你在字典上进行迭代时,你得到的是密钥迭代而不是(密钥,值)对。 HADOOP_HOME/share/hadoop/mapreduce/lib方法采用我们可以迭代的任何对象,因此您看到了差异。

您可以在迭代dict时通过prining来验证这一点:

sorted

以上所有两个for循环都打印相同的值。

答案 2 :(得分:0)

在第二个示例中,应用于字典的@Entity @Table(name = "task") public class Task { private int taskId; // other properties ... private List<ListTask> listTasks = new ArrayList<>(); public Task() { } @Id @GeneratedValue @Column(name = "taskid") public int getTaskId() { return taskId; } public void setTaskId(int taskId) { this.taskId = taskId; } // other getters and setters ... @OneToMany(mappedBy = "task", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true, fetch = FetchType.EAGER) public List<ListTask> getListTasks() { return listTasks; } public void setListTasks(List<ListTask> listTasks) { this.listTasks = listTasks; } } @Entity @Table(name = "todolist") public class TodoList { private int id; // other properties ... private List<ListTask> listTasks = new ArrayList<>(); public TodoList() { } @Id @GeneratedValue @Column(name = "todolistid") public int getId() { return id; } public void setId(int id) { this.id = id; } // other getters and setters ... @OneToMany(mappedBy = "todoList", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true, fetch = FetchType.EAGER) public List<ListTask> getListTasks() { return listTasks; } public void setListTasks(List<ListTask> listTasks) { this.listTasks = listTasks; } } @Test public void deleteTest() { Task task = ...; TodoList todoList = ...; ListTask listTask = new ListTask(); // Associate ListTask with Task first. listTask.setTask(task); task.getListTasks().add(listTask); task = taskRepository.save(task); // get the persisted ListTask then associate with TodoList listTask = task.getListTasks().toArray(new ListTask[1])[0]; listTask.setTodoList(todoList); todoList.getListTasks().add(listTask); todoList = todoListRepository.save(todoList); // Start trying different deletions task.getListTasks().clear(); taskRepository.save(task); // At this step hibernate only generated select queries, no delete ones, thus no ListTask got removed. todoList.getListTasks().clear(); todoListRepository.save(todoList); // At this step hibernate finally generated "delete from listtask where listtaskid=? ..." thus removed the ListTask. } 方法返回元组class A: def __init__(self): self.do() def do(self): print("do A") class B(A): def __init__(self): super().__init__() self.do() def do(self): super().do() print("do B") b = B() 的可迭代集合。然后正在对集合进行排序。

在第一个示例中,字典首先自动转换为其可复制的键集合。 (并注意:在排序时,只有每个人的第一个字符用于比较,这可能不是你想要的)