如何实现int列表元素与嵌套int列表元素的对应相加?
Your original code isn't working because it's creating a Cartesian product of all elements in h and n—each value in h is being added to every sublist in n, which isn't what you want. Instead, you need to process elements at the same index from both lists. Here are a couple of straightforward solutions:
Solution 1: Using Index-Based Loop
This approach explicitly iterates over each index, accessing the corresponding element from h and sublist from n:
h = [1, 2, 3, 2, 3, 3] n = [[0], [0, 1], [0, 1, 2], [0], [0, 1], [0]] result = [] for i in range(len(h)): # Get the current value from h and the matching sublist from n current_value = h[i] current_sublist = n[i] # Add current_value to every element in the sublist updated_sublist = [num + current_value for num in current_sublist] result.append(updated_sublist) print(result) # Output: [[1], [2, 3], [3, 4, 5], [2], [3, 4], [3]]
Solution 2: Pythonic List Comprehension with zip()
Using zip() is a cleaner way to pair elements from h and n directly, avoiding manual index management. This is the preferred approach in Python:
h = [1, 2, 3, 2, 3, 3] n = [[0], [0, 1], [0, 1, 2], [0], [0, 1], [0]] # Pair each value from h with its corresponding sublist from n result = [[num + val for num in sublist] for val, sublist in zip(h, n)] print(result) # Output: [[1], [2, 3], [3, 4, 5], [2], [3, 4], [3]]
Key Note:
Make sure h and n have the same length. If they don't, zip() will stop processing once it reaches the end of the shorter list. If you need to handle uneven lengths, you might want to use itertools.zip_longest instead, but that's probably not necessary for your current use case.
内容的提问来源于stack exchange,提问作者syntheso

