我试图将一组对象合并成一个对象,作为一个对象放在列表的末尾。有什么办法可以实现?
我尝试对.append使用多个参数,并尝试搜索其他函数,但到目前为止我还没有发现任何东西。
yourCards = []
cards =["Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"]
suits = ["Hearts","Diamonds","Clubs","Spades"]
yourCards.append(cards[random.randint(0,12)],"of",suits[random.randint(0,3)])
我希望列表中仅包含一个新元素,例如“两颗心”,但我却收到此错误:
TypeError: append() takes exactly one argument (3 given)
答案 0 :(得分:3)
您正在发送append()
多个参数而不是字符串。这样将参数格式化为字符串。同样,{@ {1}}比random.choice()
更好,如下面的@JaSON所述。
3.6+,使用random.randint()
f-strings
使用yourCards.append(f"{random.choice(cards)} of {random.choice(suites)}")
.format()
字符串串联
yourCards.append("{} of {}".format(random.choice(cards), random.choice(suites)))
改进Alex的yourCards.append(str(random.choice(cards)) + " of " + str(random.choice(suites)))
#You likely don't need the str() but it's just a precaution
方法
join()
答案 1 :(得分:0)
yourCards.append(' '.join([random.choice(cards), "of", random.choice(suits)]))