У меня есть два списка: < /p>
list1 = ['B, A', 'D, C', 'F, E','Y, X']
list2 = ['E B, A', 'D, C G', 'F','Y, X']
< /code>
Каждый элемент списка состоит из фамилии и имени, разделенной запятой. 'F, e'. Более того, в списке2 'e' содержится в другом элементе и, вероятно, не принадлежит элементу 'e b, «потому что' b, a 'of list1 - это часть' e b, a 'of list2.
Есть ли способ решить это?import re
from collections import defaultdict
def fix_combinations(list1, list2):
# Create a set of valid combinations from list1
set1 = {tuple(item.split(', ')) for item in list1}
# Create a dictionary to hold word associations
word_associations = defaultdict(list)
# Populate the word associations based on list1
for a, b in set1:
word_associations[a].append((a, b))
word_associations.append((a, b))
# Create a set to collect the fixed combinations
fixed_combinations = set()
# Process list2 to find valid combinations
for item in list2:
# Find all potential matches in list2 using regex
potential_matches = re.findall(r'(\w+),?\s*(\w+)', item)
if potential_matches:
for match in potential_matches:
if match in set1:
fixed_combinations.add(', '.join(match))
else:
# Check if any of the words in the match are associated with the combinations from list1
for word in match:
if word in word_associations:
for combination in word_associations[word]:
fixed_combinations.add(', '.join(combination))
break
else:
# If no direct match, check for missing combinations
for combination in set1:
fixed_combinations.add(', '.join(combination))
return list(fixed_combinations)
# Example lists
list1 = ['B, A', 'D, C', 'F, E']
list2 = ['E B, A', 'D, C G', 'F']
# Call the function and print the result
result = fix_combinations(list1, list2)
print(result)
Подробнее здесь: https://stackoverflow.com/questions/794 ... t-matching
Как сравнить два списка Python, исправить их элементы и вернуть лучшие соответствующие элементы? ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Python: сравнить два словаря, содержащие списки, и вернуть удаленные элементы
Anonymous » » в форуме Python - 0 Ответы
- 26 Просмотры
-
Последнее сообщение Anonymous
-