【问题标题】:attempting to compare to cards with different 'suits / colours' to eachother试图将两张具有不同“花色/颜色”的牌相互比较
【发布时间】:2021-12-06 17:29:06
【问题描述】:

我是 python 新手,所以如果我的卡看起来很初学者,那就是原因。

我正在尝试比较两张卡片并找出哪一张更大。在这种情况下,红色战胜黑色,黄色战胜红色,黑色战胜黄色(就像数字石头剪刀布一样)如果花色/颜色相同,我还打算比较卡片的数量

这是我目前得到的:

import random


vals = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
colours = ['red', 'yellow', 'black']

deck = list(itertools.product(vals, colours))

random.shuffle(deck)

for vals, colours in deck:
    print( str(vals) + ' ' + str(colours))




p1card = str(deck[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28])
p2card = str(deck[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29])
  

print(player_one + "'s card = " + str(p1card))
print(player_two + "'s card = " + str(p2card))

if p1card.find('red') and p2card.find('black'):
    print(player_one + ' wins!')

if p1card.find('yellow') and p2card.find('red'):
    print(player_one + ' wins!')

if p1card.find('black') and p2card.find('yellow'):
    print(player_one + ' wins!')

if p2card.find('red') and p1card.find('black'):
    print(player_two + ' wins!')

if p2card.find('yellow') and p1card.find('red'):
    print(player_two + ' wins!')

if p2card.find('black') and p1card.find('yellow'):
    print(player_two + ' wins!')

当我运行代码时出现错误:

TypeError: list indices must be integers or slices, not tuple

我不知道这意味着什么,也不知道我将如何完成这项任务,因此非常感谢任何帮助!

谢谢!

【问题讨论】:

标签: python


【解决方案1】:

这不是列表在 python 中的工作方式。你可能期待的是

deck = [0,10,20,30,40,50]
deck[0,2,4] # you want this [0, 20, 40] but an error is thrown
deck[1,3,5] # you want this [10, 30, 50] but an error is thrown

可悲的是,它不是那样工作的。您只能从中获取一个数字,如下所示:

deck = [0,10,20,30,40,50]
deck[1] # returns 10
deck[4] # returns 40
deck[1,4] # error

但是,您可以这样做:

deck = [0,10,20,30,40,50]
deck[::2] # returns [0, 20, 40]
deck[1::2] # returns [10, 30, 50]

我在这里做的事情叫slicing

【讨论】:

    猜你喜欢
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多