[英]AttributeError: 'list' object has no attribute 'replace',
testdeck = ['apple', 'banana', 'napalm', 'ice','rock','death','plush','rush']
finaldeck = [1,2,3,4,5,6,7,8]
for card in testdeck:
index = testdeck.index(card)
print('index',index,'card',card)
for item in finaldeck:
if type(item) == int:
print(item,'integer','replacing...')
finaldeck = finaldeck.replace(item,card)
elif type(item) == str:
print(item,'string'' not replacing...')
#example(end game)
exampledeck = ['banana','apple]
exmapledeck2 = [1,2,3,4]
exampledeck2 = ['banana','apple,3,4]
Finaldeck already has 8 items, each one being an integer the idea is that every string in testdeck will need to be placed in the first integer found available in finaldeck. Finaldeck 已经有 8 个项目,每个项目都是一个整数,这个想法是 testdeck 中的每个字符串都需要放在 finaldeck 中找到的第一个整数中。
You just need to use zip and enumerate together:您只需要一起使用 zip 和枚举:
testdeck = ['apple', 'banana', 'napalm', 'ice','rock','death','plush','rush']
finaldeck = [1,2,3,4,5,6,7,8]
for index, (card, item) in enumerate(zip(testdeck, finaldeck)):
if isinstance(item, int):
finaldeck[index] = card
This is a single pass through both lists at the same time, terminating at the end of the shortest list.这是同时通过两个列表的单次遍历,在最短列表的末尾终止。
replace is a string method not a list method. replace 是字符串方法而不是列表方法。
this is what you want:这就是你想要的:
finaldeck[item-1] = card
But it doesn't really make any sense, if you can please explain what you are trying to achieve maybe we can help you, you don't really need that second list.但这并没有任何意义,如果你能解释一下你想要达到的目标,也许我们可以帮助你,你真的不需要第二个列表。
btw there is a typo : finalek .顺便说一句,有一个错字: finalek 。
Since you clarified this is what I suggest you: Create a class Card既然你澄清了这就是我建议你:创建一个类卡
class Card:
def __init__(self, name, is_active = False):
self.name = name
self.is_active = is_active
def flip_card_state():
self.is_active = not self.is_active
Then init a empty array of cards然后初始化一个空的卡片数组
card_names = ['apple', 'banana', 'napalm', 'ice','rock','death','plush','rush']
deck = [Card(name = name, is_active = False) for name in card_names]
if you need to print them then you just have to check is_active如果您需要打印它们,那么您只需检查 is_active
#you can make this code a class method of Card
if deck[card_index].is_active:
print(card.name)
else:
print("The card is not active")
if you need to learn about classes: https://www.w3schools.com/python/python_classes.asp如果您需要了解课程: https ://www.w3schools.com/python/python_classes.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.