我有以下代码,我想要的是删除重复四次的列表hand
的所有值。
value=["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
sign=["T", "D", "C", "P"]
hand=["AD", "AC", "2D", "3C", "4C", "AT", "AP", "2C", "2P", "2T"]
counter1=0
counter2=0
while counter2<=12:
for x in value:
for y in sign:
z=x+y
if z in [value[counter2]+c for c in sign]:
counter1+=1
if counter1==4:
for x in [value[counter2]+c for c in sign]:
hand.remove(x)
counter1=0
counter2+=1
print(hand)
正如您所看到的,我尝试了while
循环,但它给了我ValueError
。
我该怎么办?
答案 0 :(得分:0)
如果你需要hand的值
hand=["2D", "3C", "4C", "2C", "2P", "2T"]
你需要运行
from collections import Counter
# get the values in hand
values_in_hand = [h[0] for h in hand]
# create a dict with the count of ocurrences in hand
count = Counter(values_in_hand)
# get only the items where the value is different from 4
clean_hand = [h for h in hand if count[h[0]] != 4]
答案 1 :(得分:0)
使用频率词典:
match_perm(List1, List2, MatchUp) :-
permutation(List1, PList1),
permutation(List2, PList2),
zip(Plist1, PList2, MatchUp).
答案 2 :(得分:0)
经过一些修复后,这是您的算法:
value=["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
sign=["T", "D", "C", "P"]
hand=["AD", "AC", "2D", "3C", "4C", "AT", "AP", "2C", "2P", "2T"]
counter1=0
counter2=0
while counter2<=12:
for x in value:
for y in sign:
z=x+y
if z in hand:
counter1+=1
if counter1==4:
for x in [value[counter2]+c for c in sign]:
hand.remove(x)
counter1=0
counter2+=1
print(hand)
输出:
['3C', '4C']
但您也可以按以下步骤执行此任务:
第一步:
分组所有索引[0]手中的相同项目:
compare_list={}
for i in hand:
data=list(i)
if data[0] not in compare_list:
compare_list[data[0]]=[i]
else:
compare_list[data[0]].append(i)
print(compare_list)
输出:
{'3': ['3C'], '2': ['2D', '2C', '2P', '2T'], '4': ['4C'], 'A': ['AD', 'AC', 'AT', 'AP']}
第2步:
现在从值和符号列表中创建组合:
data4=[[i+j for j in sign] for i in value]
print(data4)
将给出:
[['AT', 'AD', 'AC', 'AP', 'Ao'], ['2T', '2D', '2C', '2P', '2o'], ['3T', '3D', '3C', '3P', '3o'], ['4T', '4D', '4C', '4P', '4o'], ['5T', '5D', '5C', '5P', '5o'], ['6T', '6D', '6C', '6P', '6o'], ['7T', '7D', '7C', '7P', '7o'], ['8T', '8D', '8C', '8P', '8o'], ['9T', '9D', '9C', '9P', '9o'], ['10T', '10D', '10C', '10P', '10o'], ['JT', 'JD', 'JC', 'JP', 'Jo'], ['QT', 'QD', 'QC', 'QP', 'Qo'], ['KT', 'KD', 'KC', 'KP', 'Ko']]
Final_step:
现在只检查比较列表是否有任何项目len == 4且所有项目也存在于任何组合子列表中,然后只需删除密钥:
但是不是从原始字典中删除键,而是从那里创建一个dict和delete键的副本:
final_list=deepcopy(compare_list)
for value_1,hand_1 in compare_list.items():
if len(hand_1)==4:
for item in data4:
if set(hand_1).issubset(item) or set(item).issubset(hand_1):
del final_list[value_1]
print(final_list.values())
outout:
dict_values([['3C'], ['4C']])