我试图在每次迭代中逐个弹出列表中的所有元素,问题是Python只弹出列表的上半部分,我需要它来弹出所有这些元素。这是我的代码:
cards = ['As', 'Ks', 'Qs', 'Js', '10s', '9s', '8s', '7s', '6s', '5s', '4s', '3s', '2s',\
'Ad', 'Kd', 'Qd', 'Jd', '10d', '9d', '8d', '7d', '6d', '5d', '4d', '3d', '2d',\
'Ac', 'Kc', 'Qc', 'Jc', '10c', '9c', '8c', '7c', '6c', '5c', '4c', '3c', '2c',\
'Ah', 'Kh', 'Qh', 'Jh', '10h', '9h', '8h', '7h', '6h', '5h', '4h', '3h', '2h']
#itertools.combinations returns a tuple and we store it in tupOnePlayerAllCombos
tupOnePlayerAllCombos = itertools.combinations(cards, 2)
#We need to convert out tuple to a list in order for us to use the replace() methos, tuples do not have such a method
lstOnePlayerAllCombos = list(tupOnePlayerAllCombos)
#There are characters we need to delete from each list item, we will store each edited list item in this list
lstEditedOnePlayerAllCombos = []
#replace all useless characters in every list item ( ' and ( and ) and , )
for lstOnePlayerAllCombo in lstOnePlayerAllCombos:
lstOnePlayerAllCombo = str(lstOnePlayerAllCombo).replace("'","").replace("(","").replace(")","").replace(", ","")
#Add edited list item to our new list
lstEditedOnePlayerAllCombos.append(lstOnePlayerAllCombo)
lstEditedOnePlayerAllCombos2 = lstEditedOnePlayerAllCombos
#For every list item in our combination list
for lstEditedOnePlayerAllCombo in lstEditedOnePlayerAllCombos:
#We need to delete the current list item from the list, so that we dont get duplicate hands for other players
#so we retrieve the index by searching the list with our current value and store that value as our player1 hand
strPlayerOneHand = lstEditedOnePlayerAllCombos2.pop(lstEditedOnePlayerAllCombos.index(lstEditedOnePlayerAllCombo))
intLength = (len(lstEditedOnePlayerAllCombos2)-1)
#print (lstEditedOnePlayerAllCombos)
print("The current length of the list is " + str(intLength))
答案 0 :(得分:0)
您可以像这样删除整个列表的内容
my_list = [1, 2, 3, 4, 5]
del my_list[:]
print my_list
# []
在Python 3.x中,您可以使用list.clear
方法,就像这样
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list)
# []
如果你想在每次迭代中逐个pop
所有元素,那么
my_list = [1, 2, 3, 4, 5]
while my_list:
print my_list.pop()
# 5
# 4
# 3
# 2
# 1