我有两个列表,其值与其他位置匹配。因此Jon的得分为123,而Bede的成绩为11等。
name = ["Jon", "Bede", "Joe"]
score = [123, 11, 43]
如何订购列表,以便输出最低分,首先提升到最高分,每次输出得分者的姓名。
答案 0 :(得分:3)
for s, n in sorted(zip(score, name)): # sort by score.
print(n, s)
答案 1 :(得分:1)
如果您有两个列表,其中索引是相关的,则很难使它们保持同步。解决方案python有一个元组列表,其中每个元组中的第一个元素是名称,第二个元素是分数:
names_with_score = [
("Jon", 123),
("Bede", 11),
("Joe", 43),
]
names_with_score.sort(key=lambda x: x[1]) # sort with the second element
如果您无法控制数据的传送方式,您可以使用zip-function加入列表:
names_with_score = zip(name, score)
答案 2 :(得分:0)
这个怎么样?
Bede: 11
Joe: 43
Jon: 123
输出:
public boolean onDependentViewChanged(CoordinatorLayout parent, View child,
View dependency) {
final CoordinatorLayout.Behavior behavior =
((CoordinatorLayout.LayoutParams) dependency.getLayoutParams()).getBehavior();
if (behavior instanceof Behavior) {
// Offset the child so that it is below the app-bar (with any overlap)
final int appBarOffset = ((Behavior) behavior)
.getTopBottomOffsetForScrollingSibling();
final int expandedMax = dependency.getHeight() - mOverlayTop;
final int collapsedMin = parent.getHeight() - child.getHeight();
if (mOverlayTop != 0 && dependency instanceof AppBarLayout) {
// If we have an overlap top, and the dependency is an AppBarLayout, we control
// the offset ourselves based on the appbar's scroll progress. This is so that
// the scroll happens sequentially rather than linearly
final int scrollRange = ((AppBarLayout) dependency).getTotalScrollRange();
setTopAndBottomOffset(AnimationUtils.lerp(expandedMax, collapsedMin,
Math.abs(appBarOffset) / (float) scrollRange));
} else {
setTopAndBottomOffset(dependency.getHeight() - mOverlayTop + appBarOffset);
}
}
return false;
}
答案 3 :(得分:0)
如果你不介意的话,这会合并列表:
sorted(zip(name,score))
答案 4 :(得分:0)
尝试将它们转换为字典以便于访问,而不是坚持使用一对并行的list
。然后,您可以使用key
参数按键对字典进行排序:
name = ["Jon", "Bede", "Joe"]
score = [123, 11, 43]
results = dict(zip(name, score))
for k in sorted(results, key=results.get):
print('{}: {}'.format(k, results[k]))
结果:
Bede: 11
Joe: 43
Jon: 123