我有一个嵌套列表:
data = [[12345678, 14, 1],[135763365, 14, 0],[135763365, 12, 0],[1234, 9, 0]]
我希望找到所有子列表中的最大索引1。
为此,我创建了这个功能:
def findBusiestPeriod ():
result = max([item[1] for item in data])
counter = collections.Counter(itertools.chain(*data))
if counter[result] > 2:
# Here's where I want to find the smallest index[0] based on
# the max index[1]
return result
一旦我有列表的最大索引1
,我想检查是否有重复项(在示例中有。)如果有重复项,我想只返回最小的子列表索引0
。
我该怎么做?
答案 0 :(得分:1)
sorted()
可以使用以下密钥执行此操作:
sorted(data, key=lambda x: (-x[1], x[0]))[0]
data = [[12345678, 14, 1], [135763365, 14, 0],
[135763365, 12, 0], [1234, 9, 0]]
print(sorted(data, key=lambda x: (-x[1], x[0]))[0])
[12345678, 14, 1]
答案 1 :(得分:0)
如果某人已经显示 import React, { Component } from "react";
import { View, Text, ScrollView, StyleSheet } from "react-native";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import {
Workout,
WorkoutDetail,
KeyValueText,
DetailText
} from "../../components";
import { getWorkout } from "../../actions";
class WorkoutDetailScreen extends Component {
constructor(props) {
super(props);
this.state = {
currentWorkout: {}
};
}
componentDidMount() {
const workoutId = this.props.navigation.state.params;
this.props.getWorkout(workoutId);
this.props.navigation.setParams({}); // If I remove this line, the error goes. But I want to set params here.
}
render() {
let currentWorkout = this.props.currentWorkout;
let tools =
currentWorkout.tools && currentWorkout.tools.length > 0
? currentWorkout.tools.join(", ")
: "Not Required";
let muscles = currentWorkout.muscles
? currentWorkout.muscles.join(", ")
: "";
return (
<ScrollView style={styles.container}>
<WorkoutDetail
workout={this.props.currentWorkout}
workoutImage={currentWorkout.workoutImage}
onPressWorkout={() => alert("CONTINUE WORKOUT")}
/>
<View style={styles.workoutInfo}>
<KeyValueText header="Time" value={currentWorkout.length} />
<KeyValueText header="Difficulty" value={currentWorkout.difficulty} />
<KeyValueText header="Tools" value={tools} />
<KeyValueText header="Muscles" value={muscles} />
</View>
<View>
<DetailText text={currentWorkout.description} />
</View>
</ScrollView>
);
}
// navigation options
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerTitle: "TITLE",
headerTitleStyle: {
width: "100%",
alignItems: "center"
},
headerStyle: {
paddingRight: 10,
paddingLeft: 10
}
};
};
}
// styles
const styles = StyleSheet.create({
container: {
flex: 1
},
workoutInfo: {
paddingBottom: 10,
borderBottomWidth: 1,
borderBottomColor: "gray"
}
});
const mapStateToProps = state => {
return {
currentWorkout: state.workouts.currentWorkout
};
};
const mapDispatchToProps = dispatch => {
return {
getWorkout: bindActionCreators(getWorkout, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(
WorkoutDetailScreen
);
函数的key
参数,我想提及sorted
和min
函数也有max
参数。
key