【发布时间】:2017-06-07 23:40:07
【问题描述】:
我有一个字符串列表 - foo 和另一个整数列表 - bar,它跟踪 foo 中的重要索引。
例如:
foo = [{}.format(i) for i in range(1, 11)] # not necessarily of this format
bar = [0, 3, 5]
我想创建一个用于创建列表列表的配方,每个列表通过根据bar 中的索引拆分foo 获得。
上述示例的预期输出:
[['1', '2', '3'], ['4', '5'], ['6', '7', '8', '9', '10']]
为了实现这一点,我创建了以下工作正常的函数:
result = []
for index, value in enumerate(b):
if index == len(b) - 1:
result.append(a[value:])
elif index == 0 and value != 0:
result.append(a[0: value])
else:
result.append(a[value: b[index + 1]])
但是,由于我的 C-Java 背景,我发现此代码高度非 Pythonic。
我想知道这个问题的更好解决方案(也许我们可以使用itertools 不知何故)。
【问题讨论】:
-
典型的切片问题。也许这有帮助:stackoverflow.com/questions/509211/…
-
@JanZeiseweis 感谢您的参考,但对于这个特定问题没有多大用处。
-
@schwobaseggl 感谢您的关注。我会将其标记为重复
标签: python list python-3.x loops