如果我们有玩家A、B和C对玩家a、b和c的名义评分(如表中所示)(即,玩家A对玩家a-8、玩家b-6和玩家c-9进行评分),在Python中是否有一种方法可以对每个玩家的选择进行排序,并创建变量供以后使用?
╔════════╦═══╦═══╦═══╗
║ Player ║ a ║ b ║ c ║
╠════════╬═══╬═══╬═══╣
║ A ║ 8 ║ 6 ║ 9 ║
║ B ║ 5 ║ 7 ║ 9 ║
║ C ║ 7 ║ 8 ║ 6 ║
╚════════╩═══╩═══╩═══╝所以在这种情况下,我想要一个函数,它将A的偏好排序为c,a,b,然后创建3个变量,稍后在代码中引用;
A_Preference_1 = c
A_Preference_2 = a
A_Preference_3 = b很抱歉,如果这看起来含糊其辞,但任何建议都将非常感谢!
发布于 2017-03-15 18:58:56
我会用字典,然后你就有了所有必要的信息。
from operator import itemgetter
ratings = {
'A': {'a': 8, 'b': 6, 'c': 9},
'B': {'a': 5, 'b': 7, 'c': 9},
'C': {'a': 7, 'b': 8, 'c': 6},
}
for player, rating in ratings.items():
# Now you can find the max, sort the ratings, etc..
favorite = max(rating.items(), key=itemgetter(1))[0]
# Use str.format() if your Python version is < 3.6.
print(f"{player}'s favorite is {favorite}.")
sorted_ratings = sorted(rating.items(), key=itemgetter(1))
print(player, sorted_ratings)输出:
A's favorite is c.
A [('b', 6), ('a', 8), ('c', 9)]
B's favorite is c.
B [('a', 5), ('b', 7), ('c', 9)]
C's favorite is b.
C [('c', 6), ('a', 7), ('b', 8)]https://stackoverflow.com/questions/42806394
复制相似问题