python find all lists with the same second element
- User
python find all lists with the same second element
- Assistant
To find all lists with the same second element in Python, you can iterate over the lists and use a dictionary to group them based on their second element. Here's an example:
pythonlists = [[1, 2, 3], [4, 2, 6], [7, 8, 9], [10, 2, 12], [13, 14, 15]] result = {} for lst in lists: key = lst[1] # Get the second element if key in result: result[key].append(lst) else: result[key] = [lst] # Print the lists with the same second element for key, value in result.items(): print(f"Lists with second element {key}: {value}")Output:
codeLists with second element 2: [[1, 2, 3], [4, 2, 6], [10, 2, 12]] Lists with second element 8: [[7, 8, 9]] Lists with second element 14: [[13, 14, 15]] - User
do it without using key
- Assistant
If you want to achieve the same result without using a dictionary key, you can use a list of lists to store the grouped lists. Here's an example:
pythonlists = [[1, 2, 3], [4, 2, 6], [7, 8, 9], [10, 2, 12], [13, 14, 15]] result = [] for lst in lists: found = False for group in result: if lst[1] == group[0][1]: group.append(lst) found = True break if not found: result.append([lst]) # Print the lists with the same second element for group in result: second_element = group[0][1] print(f"Lists with second element {second_element}: {group}")Output:
code