比较2不需要模式匹配的列表



如问题所述,现在我想比较2没有模式匹配的变量列表

第一个列表变量=userList[i]

第二个列表变量=colors_code[i]

例如,

userList[i]将包含'Y'、'B'、'G'、'R'

colors_code[i]将包含"R"、"G"、"B"、"Y">

我想让我的代码比较这个2列表变量是否存在字符串,而不是模式匹配

以下是我的代码:

# Create a For-Loop to loop 4 times, since we have only 4 colors
for i in range(0, 4):
# To validate User Input & overwrite User Input into the List
if userList[i] == colors_code[i]:
count = count + 1
userList[i] = "1"
correct[i] = userList[i]
else:
continue

如果发生次数是重要的

sorted(['Y','B','G','R']) == sorted(['R','G','B','Y'])

否则

set(['Y','B','G','R']) == set(['R','G','B','Y'])

您有多种方法来确保列表的所有元素都包含在另一个列表中:

# Classic way:
flag = True
for e in list1:
if e not in list2:
flag  = False
break
if flag:
# whatever

# Using all function:
all(map(lambda e: e in list2, list1))
# Using frozen sets
FrozenSet(list1) == FrozenSet (list2)

最新更新