遍历现有列表值,同时使用列表理解来创建列表

时间:2018-12-30 18:52:56

标签: python list list-comprehension

虽然这是完全不需要的,但我仍然想尝试将所有内容放入尽可能少的代码行中,同时也使用OOP

我已经在没有OOP的情况下完成了代码,但有人问是否可以在OOP中完成,该问题可以用更多的代码行解决,但我想尽可能地将其放入1个

class Player:
    def __init__(self,x,y,z,a):
        self.id = x
        self.prompt = y
        self.score = z
        self.overall_scores = a

players = [Player(x,y,random.randint(1,6),{z.id:z.score for z in players} 
if x == 3 else None) for x,y in zip(range(0,4),["First", "Second", "Third", 
"Fourth"])]

我希望每个球员都有自己的得分,最后一位球员保持整体得分,这样我就可以根据他们的值对它们进行排序,以确定得分最高的球员。请注意,OOP不是执行此任务的最佳方法,但有人问我,OOP的外观如何

程序应该做什么:给每个球员一个随机分数,然后根据最高分数排名

编辑: 由于请求了没有OOP的代码,因此它是:

import operator,random

players = {x:0 for x in range(0,4)}
prompts = ["First", "Second", "Third", "Fourth"]

for a in players:
    players[a] = random.randint(1,6)
    print("%s:\nDice: %s" % (prompts[a],players[a]))
sorted_players = sorted(players.items(),key=operator.itemgetter(1))

draw = True
previous = 0
draw_between = []
first = True
for a in sorted_players[::-1]:
    if first:
        previous = a[1]
        first = False
    elif previous != a[1]:
        draw = False
    if draw:
        draw_between.append(a[0])

if draw:
    print("The chances of this were astronomically low but it happened anyway!")
    print("It's a draw!")
elif len(draw_between) <= 1:
    print("%s Player Wins!" % (prompts[sorted_players[-1][0]]))
else:
    out = "First place is a draw between Players:\n"
    draw_between.sort()
    for b,a in enumerate(draw_between):
        out += str(prompts[a])
        if b < len(draw_between)-1:
            out += ", "
    print(out)

1 个答案:

答案 0 :(得分:0)

注释和问题结尾表明,您不需要“总分”,也不需要收集最后一位玩家的分数。如果是这样,那么这就是您想要的,即“给每个玩家一个随机分数,然后根据最高分数排名”(我假设您希望他们从头到尾排名):

import random


class Player:
    def __init__(self, x, y, z):
        self.id = x
        self.prompt = y
        self.score = z


players = [Player(x,
                  y,
                  random.randint(1, 6))
           for x, y in zip(range(0, 4), ["First", "Second", "Third", "Fourth"])]

sorted_players = sorted([Player(x,
                                y,
                                random.randint(1, 6))
                         for x, y in zip(range(0, 4), ["First", "Second", "Third", "Fourth"])], 
                        key=lambda dude: dude.score, reverse=True)