python - Dividing a list into subsets according to a numeric array in Python
问题描述
I have a list
with characters like so:
s = ['Y', 'U', 'U', 'N', 'U', 'U', 'N', 'N', 'N']
And the following array:
t = [2, 4, 3]
I would like to divide the list according to the array, such that each subset st[i]
has len(t[i])
. Result for this example should be:
st = [['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]
If array t was:
t = [5, 2, 2]
Then the result should be:
st = [['Y', 'U', 'U', 'N', 'U'], ['U', 'N'], ['N', 'N']]
Entries are s and t. I am trying by inserting two loops, one for list s and another one for array t. But it is not working. How can I implement this?
解决方案
You can create an iterator from s
and use itertools.islice
to slice the iterator according to the sizes in t
:
from itertools import islice
i = iter(s)
[list(islice(i, l)) for l in t]
This returns:
[['Y', 'U'], ['U', 'N', 'U', 'U'], ['N', 'N', 'N']]
推荐阅读
- ios - 如何在 AppDelegate 中初始化 Core Data 的持久化容器并在整个应用程序中使用它?
- c++ - C++:实现 ln(a) 的数值逼近
- python - VBA运行python脚本 - 权限错误
- python - 根据等于熊猫数据框中特定值的列定位最小日期?
- python - 在将字符串添加到电子邮件时获取 \n
- r - 将列表转换为 R 中具有多列的 data.frame
- c++ - 将 v8 类型转换为 c++ 类型(字符串)
- javascript - How to store birthdays in a database with timezone support?
- ruby-on-rails - 导轨形式的数据列表
- c++ - 使用模板实现接口的c ++编译错误