基于for循环动态调整Zip运算符的可迭代对象数量
Dynamic Number of Arguments for
zip() in a For Loop Got it, let's tackle this problem where you want to pass a dynamic number of slice arguments to zip() based on your loop variable i.
The key insight here is using Python's argument unpacking (the * operator) to pass a list of slices directly to zip(). Instead of hardcoding each slice for every i, we can generate all required slices programmatically and unpack them into zip().
Here's the working code:
s = "abcde" for i in range(1, len(s)): # Generate all needed slices: s[0:], s[1:], ..., s[i:] slices = [s[k:] for k in range(i + 1)] # Unpack the slices list as arguments to zip() l = zip(*slices) # Print the result to verify print(f"When i = {i}:") print(list(l))
How it works:
- For each
i, we create a listslicesthat containsi+1elements:s[0:](which is justs),s[1:],s[2:], up tos[i:]. - Using
zip(*slices)unpacks the list into individual arguments forzip(). So wheni=1, this becomeszip(s, s[1:]); wheni=2, it'szip(s, s[1:], s[2:]), and so on—exactly what you need!
Output of the code:
When i = 1: [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')] When i = 2: [('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e')] When i = 3: [('a', 'b', 'c', 'd'), ('b', 'c', 'd', 'e')] When i = 4: [('a', 'b', 'c', 'd', 'e')]
This approach is clean, scalable, and avoids repetitive code—perfect for handling any length of input string s.
内容的提问来源于stack exchange,提问作者Viraat Das
相关产品推荐
相关产品推荐

