我正在快速制作游戏以获得乐趣,只是学习编码,而我似乎无法解决这个问题。
set1 = ["Horse", "Cow", "Pig", "Goat", "Chicken", "Sheep", "Donkey", "Duck", "Rabbit"]
set2 = ["Horse", "Cow", "Pig", "Goat", "Chicken", "Sheep", "Donkey", "Duck", "Rabbit"]
random.shuffle(set1,random.random)
random.shuffle(set2,random.random)
side1 = int(input("What number would you like to pick from side one?"))
side2 = int(input("What number would you like to pick from side two?"))
s1pick = set1.index(side1)
s2pick = set2.index(side2)
picks = []
我希望他们为side1
和side2
输入2个数字,然后存储来自set1
和set2
的相应值在s2pick
和s1pick
中{1}}。但我不断收到此错误消息:
Traceback (most recent call last):
File "C:/Users/Me/PycharmProjects/nice memes/src/snap.py", line 26, in <module>
s1pick = set1.index(side1)
ValueError: 4 is not in list
在pycharm社区版上使用python 3。谢谢!
答案 0 :(得分:0)
list.index()
返回您传递给它的元素值的索引。因此,对于列表l = ['a', 'b', 'c']
,l.index('b')
将返回1
。
如果你想转向另一个方向,获取索引的值,那么你应该使用项目访问语法:
>>> l = ['a', 'b', 'c']
>>> l[1]
'b'
因此,在您的情况下,您希望使用set1[side1]
来获取用户从set1
中选择的值。
答案 1 :(得分:0)
index()
actually returns the index of the value that you pass to the method。您收到错误,因为值4
不在您调用index()
方法的列表中。如果您在从用户那里获得提示后已经将提示转换为int()
,那么您可以指定您希望列表中的该索引处的元素如下:
s1pick = set1[side1]
s2pick = set2[side2]
但是,要小心。您获得的input()
可能超出了您的列表范围。所以,我会把你的输入放到while循环中,以确保你得到一个有效的输入:
side1 = # input code
side2 = # input code
while side1 not in range(len(set1)) or side2 not in range(len(set2)):
side1 = # input code
side2 = # input code
答案 2 :(得分:0)
比较两段代码:
list1 = ["Horse", "Cow", "Pig", "Goat", "Chicken", "Sheep", "Donkey", "Duck", "Rabbit"]
list2 = ["Horse", "Cow", "Pig", "Goat", "Chicken", "Sheep", "Donkey", "Duck", "Sheep"]
######################
index1 = 2
index2 = 3
element1 = list1[index1]
element2 = list2[index2]
print (element1) # output: Pig
print (element2) # output: Goat
######################
index1 = list1.index("Sheep")
index2 = list2.index("Donkey")
print (index1) # output: 5
print (index2) # output: 6