我有一个数字列表,我想根据多个元组列表给出的数字范围进行切片。例如,我有一个看起来像的列表:
my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,]
我还有一个元组列表,它们是我想要的值的标记:
my_tups = [(5,9), (14,18)]
如何使用my_tups作为索引仅返回my_list的值?
答案 0 :(得分:3)
使用列表理解:
my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,]
my_tups = [(5,9), (14,18)]
new_list = [my_list[i:j] for i,j in my_tups]
发表评论后:
my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0]
my_tups = [(5,9), (14,18)]
new_list = [0 for i in my_list] # Create a list filled with zeros
for i,j in my_tups:
new_list[i:j] = my_list[i:j] # Replace items with items from my_list using the indexes from my_tups
输出:
>>> new_list
[0, 0, 0, 0, 0, 1, 3, 4, 8, 0, 0, 0, 0, 0, 21, 34, 25, 91, 0, 0, 0]
答案 1 :(得分:1)
您可以使用内置slice,如下所示
my_list = [5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0]
my_tups = [(5, 9), (14, 18)]
my_list2 = [my_list[slice(*o)] for o in my_tups]
print(my_list2)
>>> [[1, 3, 4, 8], [21, 34, 25, 91]]
答案 2 :(得分:0)
可能性
from itertools import chain
my_iter = chain(*[my_list[start:end] for start, end in my_tups])
[l for l in my_iter]
给出
[1, 3, 4, 8, 21, 34, 25, 91]
答案 3 :(得分:0)
如果我正确理解了问题,您希望在范围my_list
和5:9
中返回14:18
中的值。以下代码应该这样做
my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0]
my_tups = [(5,9), (14,18)]
def flattens(lists):
return sum(lists, [])
flatten([my_list[lo:hi] for (lo, hi) in my_tups])
# gives [1, 3, 4, 8, 21, 34, 25, 91]
答案 4 :(得分:0)
您还可以将slice
与itertools.starmap
:
from itertools import starmap
my_list = [ 5., 8., 3., 0., 0., 1., 3., 4., 8., 13., 0., 0., 0., 0., 21., 34., 25., 91., 61., 0., 0.]
my_tups = [(5,9), (14,18)]
result = [my_list[slc] for slc in starmap(slice, my_tups)]
# [[1.0, 3.0, 4.0, 8.0], [21.0, 34.0, 25.0, 91.0]]
使用starmap
,您可以随意为任意切片添加步参数:
>>> my_tups = [(5,9,2), (14,18)] # step first slice by 2
>>> [my_list[slc] for slc in starmap(slice, my_tups)]
[[1.0, 4.0], [21.0, 34.0, 25.0, 91.0]]
答案 5 :(得分:0)
这应该可以解决问题:
for a, b in my_tups:
print(my_list[a:b])
您可以使用列表执行其他操作,而不是打印。
答案 6 :(得分:0)
你可以在列表理解上做这样的事情
slices = [my_list[x:y] for x, y in my_tups if x < len(my_list) and y < len(my_list)]