如何计算嵌套列表元素相对频率及跨列表对比比值?
Solution to Calculate Element Frequency Ratios Across Nested Lists
Step 1: Break Down the Calculation Rules
For every element in each list, we need two key values:
- X: (Number of sublists the element appears in the target list) / (Total sublists in the target list)
- Y: (Total times the element appears in all other lists) / (Total sublists across all other lists)
We then keep the ratio max(X/Y, Y/X) only if it’s greater than 1, linking it to the target list.
Example Walkthrough (Element 'a' in List A)
Using the provided sample data:
- List A has 4 sublists, and 'a' shows up in 2 →
X = 2/4 = 0.5 - Lists B and C combined have 3 + 2 = 5 sublists, and 'a' appears in 1 →
Y = 1/5 = 0.2 - The ratio is
0.5 / 0.2 = 2.5(since this is greater than 1)
Step 2: Python Implementation
Here’s a straightforward script to automate this calculation:
from collections import defaultdict # Define the input nested lists list_data = { 'A': [['a','b','c'],['b','d'],['c','d','e'],['a','c','e','f']], 'B': [['a','b','c'],['c','e'],['c','e']], 'C': [['b','c','e'],['b','c','e','g']] } # Precompute helper values sublist_counts = {name: len(sublists) for name, sublists in list_data.items()} elem_sublist_occurrences = defaultdict(lambda: defaultdict(int)) # Count how many sublists each element appears in per list for list_name, sublists in list_data.items(): for sublist in sublists: unique_elements = set(sublist) # Avoid counting duplicates in one sublist for elem in unique_elements: elem_sublist_occurrences[list_name][elem] += 1 # Calculate the required ratios final_ratios = defaultdict(lambda: defaultdict(float)) for target_list in list_data.keys(): # Get all other lists excluding the target other_lists = [name for name in list_data.keys() if name != target_list] total_other_sublists = sum(sublist_counts[name] for name in other_lists) for elem in elem_sublist_occurrences[target_list]: # Compute X x_value = elem_sublist_occurrences[target_list][elem] / sublist_counts[target_list] # Compute Y total_elem_other = sum(elem_sublist_occurrences[lst].get(elem, 0) for lst in other_lists) y_value = total_elem_other / total_other_sublists if total_other_sublists > 0 else 0 # Calculate valid ratio (only keep if >1) if x_value == 0 or y_value == 0: ratio = float('inf') if x_value > 0 else 0 # Handle elements unique to one list else: ratio = max(x_value / y_value, y_value / x_value) if ratio > 1: final_ratios[target_list][elem] = ratio # Print formatted results for list_name, ratios in final_ratios.items(): print(f"List {list_name}:") for elem, ratio in ratios.items(): print(f" {elem}: {ratio:.2f}")
Step 3: Code Explanation
- Precomputation: We first count how many sublists each list has, and track how many sublists each element appears in (using sets to avoid overcounting duplicates within a single sublist).
- Ratio Calculation: For each element in each list:
- Compute X using the target list’s sublist count and the element’s occurrence count.
- Compute Y by summing the element’s occurrences across all other lists, divided by their total sublists.
- Keep the larger of the two possible ratios only if it exceeds 1.
- Result Handling: Elements unique to one list will show
inf(infinity) since Y becomes 0.
Sample Output
Running the script will produce:
List A: a: 2.50 d: 2.00 f: inf List B: a: 1.67 List C: g: inf
内容的提问来源于stack exchange,提问作者Ankita Patnaik
相关产品推荐
相关产品推荐

