Как избежать дублирования слов в массиве. В следующем сценарии
First scenario: Я хочу, чтобы в выводе присутствовали все три игрока, включая Фила. Phil является подмножеством Phillies, поэтому его не следует удалять из вывода.
Second scenario: Но я хочу, чтобы в выводе присутствовали «Нью-Йорк Метс», «Филадельфия Филлис», но Филлис следует удалить, поскольку оно соответствует слову в Филадельфия Филлис
Third scenario: Я хочу, чтобы в выводе присутствовал только Криштиану Роналду, поскольку Криштиану уже присутствует как часть более крупного слова, его следует удалить.
# Initial array
football_players = ["New York Mets", "Philadelphia Phillies", "Phil"]
# football_players = ["New York Mets", "Philadelphia Phillies", "Phillies"]
# football_players = ["Cristiano", "Cristiano Ronaldo"]
# Function to remove smaller words contained in larger words
def remove_subwords(players):
result = []
for player in players:
# Check if the player name is a substring of any other name in the list
if not any(player in other and player != other for other in players):
result.append(player)
return result
# Call the function and print the result
filtered_players = remove_subwords(football_players)
print(filtered_players)
Подробнее здесь: https://stackoverflow.com/questions/790 ... n-an-array