我可以让这段代码更短或更好吗?

时间:2018-04-01 16:05:59

标签: python

我可以让这段代码更短或更好吗? 因为我觉得if行不是很好

import random as ra

out = ['rock', 'paper', 'scissor']


def match():
    p1, p2 = ra.choice(out), ra.choice(out)
    print('P1:', p1, 'x', 'P2:', p2)
    if p1 == p2:
        print('Draw', '\n')
    elif (p1 == 'rock' and p2 == 'scissor') or (p1 == 'paper' and p2 == 'rock') or (p1 == 'scissor' and p2 == 'paper'):
        print('P1 win', '\n')
    else:
        print('P2 win', '\n')


for i in range(10):
    match()

2 个答案:

答案 0 :(得分:2)

更好?我不知道。短?是的。虽然不是很多。

import random as ra
gestures = ['rock', 'paper', 'scissors'] # order here is important
def match():
    p1, p2 = ra.randint(0, 2), ra.randint(0, 2)
    print(f"P1: {gestures[p1]} x P2: {gestures[p2]}")
    if p1 == p2:
        print("tie")
    else:
        print(f"p{(p1-p2)%3} won")

for i in range(10):
    match()

可以更短

import random as ra
def rock_paper_scissors():
    gestures = ['rock', 'paper', 'scissors'] # order here is important
    p1, p2 = ra.randint(0, 2), ra.randint(0, 2)
    return "P1: {0}, x P2: {1}, Result: {2}".format(gestures[p1], gestures[p2], {0: 'tie', 1: 'p1', 2: 'p2'}[(p1-p2)%3])

for i in range(10):
    print(match())

答案 1 :(得分:0)

我声称这是更短更好

from random import choice

BEATEN_BY = {'rock': ['scissors'], 'paper': ['rock'], 'scissors': ['paper']}

def match(p1, p2):
    print('P1:', p1, 'x', 'P2:', p2)

    if p1 == p2:
        print('Draw\n')
    else:
        print('P1' if p2 in BEATEN_BY[p1] else 'P2', 'wins\n')

for _ in range(10):
    choices = list(BEATEN_BY)

    match(choice(choices), choice(choices))

虽然看起来我浪费了值列表而不是字符串,而使用in而不是==,这就是更好再次出现的地方,就像现在一样我们可以简单地做:

BEATEN_BY = {
    'rock': ['scissors', 'lizard'],
    'paper': ['rock', 'Spock'],
    'scissors': ['paper', 'lizard'],
    'lizard': ['paper', 'Spock'],
    'Spock': ['rock', 'scissors']
}