根据 Python 中的数值数组将列表划分为子集

Dividing a list into subsets according to a numeric array in Python

我有一个 list,字符如下:

s = ['Y', 'U', 'U', 'N', 'U', 'U', 'N', 'N', 'N']

以及以下数组:

t = [2, 4, 3]

我想根据数组划分列表,这样每个子集 st[i] 都有 len(t[i])。此示例的结果应为:

st = [['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]

如果数组 t 是:

t = [5, 2, 2]

那么结果应该是:

st = [['Y', 'U', 'U', 'N', 'U'], ['U', 'N'], ['N', 'N']]

条目是 s 和 t。我正在尝试插入两个循环,一个用于列表 s,另一个用于数组 t。但它不起作用。我该如何实施?

基本上你可以使用:

s = ['Y', 'U', 'U', 'N', 'U', 'U', 'N', 'N', 'N']
t = [2, 4, 3]
st = []
offset = 0
for size in t:
    st.append(s[offset:size+offset])
    offset += size

print(st)

对于 [2, 4, 3] 的输入,起始索引为:

  • 0
  • 0 + 2 = 2
  • 0 + 2 + 4 = 6

您可以使用itertools.accumulate()收集起始索引。

一旦起始索引已知,我们只需要通过 zip() 将它们与每个起始索引要分组的项目数配对,这已经是列表 [2, 4, 3] 的内容。因此:

  • 开始 0 : 计数 2
  • 开始 2:计数 4
  • 开始 6 : 计数 3

或者如评论中提到的@don'ttalkjustcode,我们也可以跟踪累积停止指数:

  • 开始 (2 - 2 = 0) : 停止 2
  • 开始 (6 - 4 = 2) : 停止 6
  • 开始 (9 - 3 = 6) : 停止 9
from itertools import accumulate

s = ['Y', 'U', 'U', 'N', 'U', 'U', 'N', 'N', 'N']

for t in [
    [2, 4, 3],
    [5, 2, 2],
    [1, 2, 6],
    [6, 1, 2],
    [2, 1, 4, 3],
    [2, 1, 2, 2, 1, 1],
]:
    # Option 1: Using start/count logic
    z = [s[start:start+count] for start, count in zip(accumulate([0] + t), t)]

    # Option 2: Using stop/count logic (thanks to @don'ttalkjustcode for pointing this out!)
    # z = [s[stop-count:stop] for stop, count in zip(accumulate(t), t)]

    print(z)

输出

[['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]
[['Y', 'U', 'U', 'N', 'U'], ['U', 'N'], ['N', 'N']]
[['Y'], ['U', 'U'], ['N', 'U', 'U', 'N', 'N', 'N']]
[['Y', 'U', 'U', 'N', 'U', 'U'], ['N'], ['N', 'N']]
[['Y', 'U'], ['U'], ['N', 'U', 'U', 'N'], ['N', 'N']]
[['Y', 'U'], ['U'], ['N', 'U'], ['U', 'N'], ['N'], ['N']]

您可以通过从 s:

的副本中迭代雕刻块来实现您想要的结果
i = 0
result = []
s_copy = s.copy()

while s_copy:
    result.append(s_copy[:t[i]])
    s_copy = s_copy[t[i]:]
    i += 1

您可以从 s 创建迭代器并使用 itertools.islice 根据 t:

中的大小对迭代器进行切片
from itertools import islice

i = iter(s)
[list(islice(i, l)) for l in t]

这个returns:

[['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]