You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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 list slices that contains i+1 elements: s[0:] (which is just s), s[1:], s[2:], up to s[i:].
  • Using zip(*slices) unpacks the list into individual arguments for zip(). So when i=1, this becomes zip(s, s[1:]); when i=2, it's zip(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:34:15