List 根据某个属性值 排序放在第一位
时间: 2023-08-18 07:04:02 浏览: 272
您可以使用 Python 中的 `sort()` 方法来对一个 List 进行排序。如果您想根据某个属性值将某个元素放在第一位,可以使用 `key` 参数来指定排序的依据。例如,假设您有一个包含多个字典的 List,每个字典都有一个名为 `priority` 的属性,您希望将 `priority` 属性值为 `1` 的元素放在第一位,可以这样实现:
```python
my_list = [{'name': 'John', 'priority': 2}, {'name': 'Mary', 'priority': 1}, {'name': 'Bob', 'priority': 1}]
my_list.sort(key=lambda x: x['priority'] != 1)
```
这个 lambda 表达式会将 `priority` 属性值为 `1` 的元素排在前面,其他元素排在后面。这样排序后,`my_list` 的第一个元素就是 `priority` 属性值为 `1` 的元素。
相关问题
java 中 List 根据某个属性值 排序放在第一位
在 Java 中,您可以使用 `Collections` 类的 `sort()` 方法来对一个 `List` 进行排序。如果您想根据某个属性值将某个元素放在第一位,可以使用 `Comparator` 接口来指定排序的依据。例如,假设您有一个包含多个对象的 `List`,每个对象都有一个名为 `priority` 的属性,您希望将 `priority` 属性值为 `1` 的对象放在第一位,可以这样实现:
```java
Collections.sort(myList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getPriority() == 1 && o2.getPriority() != 1) {
return -1;
} else if (o1.getPriority() != 1 && o2.getPriority() == 1) {
return 1;
} else {
return 0;
}
}
});
```
这个 `Comparator` 实现会将 `priority` 属性值为 `1` 的对象排在前面,其他对象排在后面。这样排序后,`myList` 的第一个元素就是 `priority` 属性值为 `1` 的对象。
java 8 中 List 根据某个属性值 排序放在第一位
在 Java 8 中,您可以使用 `Comparator` 接口的 `comparing()` 方法和 `thenComparing()` 方法来对一个 `List` 进行排序。如果您想根据某个属性值将某个元素放在第一位,可以使用 `Comparator` 接口来指定排序的依据。例如,假设您有一个包含多个对象的 `List`,每个对象都有一个名为 `priority` 的属性,您希望将 `priority` 属性值为 `1` 的对象放在第一位,可以这样实现:
```java
List<MyObject> myList = ...;
Collections.sort(myList, Comparator.comparing(o -> o.getPriority() == 1 ? 0 : 1)
.thenComparing(Comparator.comparing(MyObject::getOtherProperty)));
```
这个 `Comparator` 实现会将 `priority` 属性值为 `1` 的对象排在前面,其他对象排在后面;然后再按照其他属性进行排序。这样排序后,`myList` 的第一个元素就是 `priority` 属性值为 `1` 的对象。
阅读全文
相关推荐
















