5 回答

TA貢獻1886條經驗 獲得超2個贊
您可以通過迭代子字符串列表來實現(xiàn)此目的,并測試 中的任何鍵字符串是否包含此子字符串,即:array2array1
for string in array2:
if not any(string in key_string for key_string in array1):
print("No key for value: " + string)
break
else:
print("All elements of array2 exist in array1")
如果您不熟悉 的子句,這將僅在循環(huán)正常退出時執(zhí)行,即如果用于提前終止循環(huán),則不會執(zhí)行。elseforbreak
如果要記錄所有不存在的子字符串:
missing = [string for string in array2
if not any(string in ks for ks in array1)]
if missing:
for string in missing:
print("No key for value: " + string)
else:
print("All elements of array2 exist in array1")

TA貢獻1998條經驗 獲得超6個贊
這是我能夠為您的問題制作的方法,
def missing(arr1, arr2):
#arr1 is the array of strings to be searched
#arr2 is the array of substrings
notFound=""
for i in arr2: # i = each element in array 2
for j in arr1: # j = each element in array 1
if i in j: # if substring of i is in an element in j
break # moves onto next element in the array
elif j == arr1[-1]: # if not found in the string, checks if on the last item in the array.
notFound = notFound+" "+i
if notFound != "":
print("No key for value:", notFound)
else:
print("all elements of array2 exist in array1")

TA貢獻1794條經驗 獲得超8個贊
sum_array1 =""
for string1 in array1:
sum_array1 = sum_array1 + string1 + ","
missing = [string2 for string2 in array2 if string2 not in sum_array1]
if missing:
for string in missing:
print("No key for value: " + string)
else:
print("All elements of array2 exist in array1")

TA貢獻1829條經驗 獲得超6個贊
在一行中:
print(
"No key for value(s): {}".format(
" ".join([k for k in array2 if not any(k in v for v in array1) ])
)
)
或者,如果您想更正確地處理所有值存在的情況
no_match = [k for k in array2 if not any(k in v for v in array1) ]
print(
"No key for value(s): {}".format(" ".join(no_match))
if no_match
else "All keys have values"
)

TA貢獻1848條經驗 獲得超6個贊
array1 = ['key/value/one123904', 'key/value/two342389', 'key/value/three234093']
array2 = ['one', 'two', 'three', 'four']
def does_match_in_array_of_string(key: str, search_list : list) -> bool:
for item in search_list:
if key in item:
return True
return False;
match_failures = [key for key in array2 if not does_match_in_array_of_string(key, array1)]
if len(match_failures):
print(f'No key for values: {match_failures}')
else:
print('All keys have values')
添加回答
舉報