在一个列表中找到具有一个或多个相同元素的列表列表合并python
时间: 2024-05-08 15:19:23 浏览: 12
Sure, I can help you with that! Here's one way to merge a list of lists in Python if they have one or more common elements:
```
def merge_lists(lists):
merged = [lists[0]]
for lst in lists[1:]:
shared = False
for i in range(len(merged)):
if len(set(lst) & set(merged[i])) > 0:
merged[i] = list(set(merged[i] + lst))
shared = True
break
if not shared:
merged.append(lst)
return merged
```
This function takes a list of lists as input, and returns a new list of lists where any lists that have one or more shared elements are combined into a single list. Here's an example usage:
```
>>> lists = [['a', 'b', 'c'], ['c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j']]
>>> merge_lists(lists)
[['a', 'b', 'c', 'd', 'e'], ['f', 'g'], ['h', 'i', 'j']]
```
In this example, the first two lists have the shared element 'c', so they are merged into a single list that includes all of their elements.